连接字符串时添加新行?

时间:2017-08-19 21:24:25

标签: r string

我有以下句子,我想将它们组合在一起,但我希望第二句开头作为一个新的段落:

Sentence 1: Premise: R is very useful for automating tasks at the office.
Sentence 2: Conclusion: Therefore, we should learn R.

我希望这两句话看起来如下:

Premise: R is very useful for automating tasks at the office.

Conclusion: Therefore, we should learn R.

这是我到目前为止所尝试的内容:

sen.1 <- "Premise: R is very useful for automating tasks at the office."
sen.2 <- "Conclusion: Therefore, we should learn R."
paragrah <- cat(sen.1, sen.2)

paragraph
Premise: R is very useful for automating tasks at the office. Conclusion: Therefore, we should learn R.

提前致谢!

3 个答案:

答案 0 :(得分:4)

您只需要插入两个换行符(\n):

sen.1 <- "Premise: R is very useful for automating tasks at the office."
sen.2 <- "Conclusion: Therefore, we should learn R."

# for printing directly, use `cat`
cat(sen.1, sen.2, sep = "\n\n")
#> Premise: R is very useful for automating tasks at the office.
#> 
#> Conclusion: Therefore, we should learn R.

# for saving as a variable for future printing, use `paste`
paragraph <- paste(sen.1, sen.2, sep = "\n\n")

# the print method of character vectors doesn't respect newlines...
paragraph
#> [1] "Premise: R is very useful for automating tasks at the office.\n\nConclusion: Therefore, we should learn R."

# ...so use `cat`
cat(paragraph)
#> Premise: R is very useful for automating tasks at the office.
#> 
#> Conclusion: Therefore, we should learn R.

答案 1 :(得分:1)

我们可以使用localhost函数,它将分隔的字符串打印到不同的行。

writeLines

答案 2 :(得分:1)

\n代表cat中的换行符,但请注意,它不会返回任何值 - 只需打印到控制台,显然您可以使用capture.output来处理...

paragrah  <- capture.output(cat(sen.1, "\n\n", sen.2))
paragrah

[1] "Premise: R is very useful for automating tasks at the office. "
[2] ""                                                              
[3] " Conclusion: Therefore, we should learn R." 

# Or simply
cat(sen.1, "\n\n", sen.2)
Premise: R is very useful for automating tasks at the office. 

 Conclusion: Therefore, we should learn R.