39

I would like to store this output in a string:

> x=1:5
> cat("hi",x)
hi 1 2 3 4 5

So I use paste, but I obtain this different result:

> paste("hi",x)
[1] "hi 1" "hi 2" "hi 3" "hi 4" "hi 5"

Any idea how to obtain the string:

"hi 1 2 3 4 5"

Thank you very much!

kahlo
  • 2,314
  • 3
  • 28
  • 37

3 Answers3

61

You can force coercion to character for x by concatenating the string "hi" on to x. Then just use paste() with the collapse argument. As in

x <- 1:5
paste(c("hi", x), collapse = " ")

> paste(c("hi", x), collapse = " ")
[1] "hi 1 2 3 4 5"
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
10

You could use capture.output with cat

capture.output(cat('hi',x))
[1] "hi 1 2 3 4 5"
mnel
  • 113,303
  • 27
  • 265
  • 254
5

You use sprintf:

> x=1:5
> str=sprintf("hi %d",x)
> str
[1] "hi 1" "hi 2" "hi 3" "hi 4" "hi 5"
> 
loretoparisi
  • 15,724
  • 11
  • 102
  • 146