Concatenate numerical values in a string

kahlo picture kahlo · Nov 7, 2012 · Viewed 77k times · Source

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!

Answer

Gavin Simpson picture Gavin Simpson · Nov 7, 2012

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"