开发者

Concatenate unwantedly applies max character width

开发者 https://www.devze.com 2023-04-08 03:50 出处:网络
I am trying to print some mixed text and variables, all on one line. c() unwantedly forces all character fields to be the width of the largest field, i.e. 12 chars in this case. How to just get simple

I am trying to print some mixed text and variables, all on one line. c() unwantedly forces all character fields to be the width of the largest field, i.e. 12 chars in this case. How to just get simple concatenation?

> print(c('Splitting col',i,'x<', xsplitval),quote=FALSE)
[1] Splitting开发者_运维问答 col 9             x<            6.7   

(I already checked all the SO questions, and all the R documentation, on print, options, format, and R mailing-lists, and Google, etc.)


You probably want to use paste:

i <- 9
xsplitval <- 6.7

paste('Splitting col',i,'x<', xsplitval, sep="")
[1] "Splitting col9x<6.7"


Another option is to use the sprintf function, which allows some number formatting:

i <- 9
xsplitval <- 6.7
sprintf("Splitting col %i, x<%3.1f", i, xsplitval)


I suggest the concatenate and print function, cat, for this purpose. Another option is message, which sends the output to stderr.

> i <- 9
> xsplitval <- 6.7
> cat('Splitting col ',i,' x<', xsplitval, '\n', sep="")
Splitting col 9 x<6.7
> message('Splitting col ',i,' x<', xsplitval, sep="")
Splitting col 9 x<6.7

c is the function for combining values into a vector; it lines up the result into equally spaced columns to make looking at resulting vector easier.

> c('Splitting col ',i,' x<', xsplitval)
[1] "Splitting col " "9"              " x<"            "6.7"  

paste concatenates character vectors together, and sprintf is like the C function, but both return character vectors, which are output (by default) with quotes and with numbers giving the index that each line of output starts with, so you may want to wrap them in cat or message.

> s1 <- paste('Splitting col ',i,' x<', xsplitval, sep=""); s1
[1] "Splitting col 9 x<6.7"
> cat(s1,'\n')
Splitting col 9 x<6.7 

> s2 <- sprintf("Splitting col %i, x<%3.1f", i, xsplitval); s2
[1] "Splitting col 9, x<6.7"
> cat(s2,'\n')
Splitting col 9, x<6.7 
0

精彩评论

暂无评论...
验证码 换一张
取 消