[R] most stable way to output text layout

Jim Lemon drj|m|emon @end|ng |rom gm@||@com
Sun Jun 13 00:40:38 CEST 2021


Hi Jeremie,
Or assuming that the matrix will always contain strings:

tabify<-function(x,col_names=NULL) {
 # convert NAs to "NA"
 x[is.na(x)]<-"NA"
 # if this matrix doesn't have any column names
 if(is.null(col_names)) col_names<-LETTERS[1:ncol(x)]
 # get the format argument for sprintf
 tab_width<-max(nchar(c(col_names,x)))+1
 # display the column names
 cat(format(col_names,width=tab_width),"\n")
 # display the matrix
 apply(x,1,function(x) cat(format(x,width=tab_width),"\n"))
}
tabify(mat)
mat_names<-c("first","second","third","fourth","fifth","sixth","seventh",
 "eighth","ninth","tenth")
tabify(mat,mat_names)

Jim

On Sun, Jun 13, 2021 at 2:25 AM Jeremie Juste <jeremiejuste using gmail.com> wrote:
>
> Hello,
>
> I'm trying to print a razor thin front-end using just text matrices and
> the command prompt.
>
> I admit that it is a bit crazy, it seems to do the job and is very quick
> to implement...  Except that I don't know of to fix the layout.
>
> I'm just seeking to map column names to a standard domain in an
> interactive way.
>
> For instance, at one iteration, the following matrix is produced:
>
> mat <- structure(c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
> NA, NA, NA, NA, NA, NA, NA, "a", "b", "c", "d", "e", "f", "g",
> "h", "i", "j", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
> NA, NA, NA, NA, NA, NA, NA, NA, "n_missing:", "n_unique:", "freq:",
> NA, NA, NA, NA, NA, NA, NA, "0", "10", NA, "a", "1", NA, NA,
> NA, NA, NA, NA, NA, NA, "b", "1", NA, NA, "best match: [1]:",
> NA, NA, NA, NA, NA, "c", "1", NA, NA, "foo", NA, NA, NA, NA,
> NA, "d", "1", NA, NA, NA, NA, NA), .Dim = c(10L, 10L))
>
>
> which I represent in the console using the following command
>
>
>     apply(
>       mat,1,
>       function(x) {
>         x[is.na(x)] <-""
>         cat(x,"\n")
>       })
>
> Do you have any suggestion for how can I have better control on the
> print layout of the  matrix so that I can fix the width of each cell?
>
> Best regards,
> --
> Jeremie Juste
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list