简体   繁体   中英

Collapse character vector into single string with each string on its own row

How do you collapse a character vector with multiple strings into a single string and with spacing between each string so that each string will start on a new line/row in the collapsed string?

I have a multiple string character vector like this:

text <- c("This should be first row", "This should be second row", "This should be third row")

I would like to collapse it into a single string, but create spacing so that each string have an individual row. Essentially, I want the string to look like the output from cat(paste()).

cat(paste(text, collapse = "\n"))

However, if try to store the output from cat(paste(text, collapse = "\n")), the object returns as NULL.

test <- cat(paste(text, collapse = "\n"))

Any suggestions for a solution?

There is no way to create an object that stores data in the way that you want except when you parse the \n characters. Whitespace in strings are meaningful, ie spaces will be preserved when a string is printed. However, how those whitespaces appear in your console will vary for a number of reasons. As it is now, your string already has the characters to tell other functions that will process it to print each substring on its own line.

text <- c("This should be first row",
          "This should be second row",
          "This should be third row")

# This is what you did
# Notice that you can't assign to an object and it prints to console!
test <- cat(paste(text, collapse = "\n"))
#> This should be first row
#> This should be second row
#> This should be third row

print(test)
#> NULL

# This is what you want: sending the object itself
test2 <- paste(text, collapse = "\n")

print(test2)
#> [1] "This should be first row\nThis should be second row\nThis should be third row"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM