kahlo kahlo - 3 months ago 20
R Question

Concatenate numerical values in a string

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

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"