Max
Max

Reputation: 35

Separating Multiple Strings in Paste() with Newline

I have a bunch of strings, like

x <- "hello"
y <- "world"
z <- "!'

And I want the output to be

"hello"
"world"
"!"

I thought what I was supposed to do was use sep = "\n" in paste(), i.e. paste(x, y, z, sep = "\n"). But this doesn't seem to be quite working, as it just puts the strings into 1 paragraph, like "hello world !". What am I doing wrong with paste()? What should the correct code be? Thank you.

Upvotes: 1

Views: 1519

Answers (2)

MKR
MKR

Reputation: 20095

The way paste has been called by OP it should have collapsed x, y and z as per expectation.

paste(x, y, z, sep = "\n")
#[1] "hello\nworld\n!"

Notice that \n is not converted in new-line. The reason is that \n works with cat.

To see the result in multi-line cat should have used. The cat transform \n in new line.

cat(paste(x, y, z, sep = "\n"))
#hello
#world
#!

Another option could be to use just cat

cat(x, y, z, sep = "\n")
#hello
#world
#!

OR

cat(c(x, y, z), sep = "\n")
#hello
#world
#!

OR

cat(sprintf("%s\n%s\n%s", x,y,z))
#hello
#world
#!

Upvotes: 1

JeanVuda
JeanVuda

Reputation: 1778

Try this:

paste(c(x, y, z), collapse = "\n")

Upvotes: 2

Related Questions