0

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.)

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142
smci
  • 32,567
  • 20
  • 113
  • 146

3 Answers3

4

You probably want to use paste:

i <- 9
xsplitval <- 6.7

paste('Splitting col',i,'x<', xsplitval, sep="")
[1] "Splitting col9x<6.7"
Andrie
  • 176,377
  • 47
  • 447
  • 496
  • No, *`paste`* is not mentioned at all on the *`concatenate page`* of R(v2.13.1 for Windows). Nor is it referenced **anywhere** in the documentation on printing. The printing examples use *`c()`*. Huge omission. – smci 7 mins ago – smci Sep 27 '11 at 08:25
  • 1
    Yes, well, `??concatenate` brings up `paste` just fine. Somehow I doubt you read the R-intro manual(s) very carefully. – Carl Witthoft Sep 27 '11 at 12:22
  • I find the `?print` documentation more helpful; it mentions using `cat` for more customizable printing. – Aaron left Stack Overflow Sep 27 '11 at 14:59
  • @smci: perhaps you were looking at the `?c` help page? There's no function called `concatenate` in R; the closest function is `paste` itself. – Aaron left Stack Overflow Sep 27 '11 at 15:29
1

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)
Karsten W.
  • 17,826
  • 11
  • 69
  • 103
1

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 
Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142