R - new line in paste() function [duplicate]

孤人 提交于 2019-12-20 18:25:11

问题


How can we insert a new line when using the function paste() or any function that concatenates strings in R?

There are many web pages on this topic but none answers clearly or gives a solution that works. I precise I don't want to use the function cat, I need to work with string of characters. Here are all my attempts (derived from all the suggestions on from different forum), they all fail...

1st Try: paste()

msg <- "==================================================\n"
msg <- paste(msg, "Var:")
print(msg)

Output:

[1] "==================================================\n Var:"

2nd Try: paste0()

msg <- "==================================================\n"
msg <- paste0(msg, "Var:")
print(msg)

Output:

[1] "==================================================\nVar:"

3rd Try: sep

msg <- "=================================================="
msg <- paste(msg, "Var:", sep = "\n")
print(msg)

Output:

[1] "==================================================\nVar:"

4th Try: sprintf

msg <- sprintf("==================================================\n")
msg <- paste(msg, "Var:")
print(msg)

Output:

[1] "==================================================\nVar:"

I believe I've tried everything I could... If you have an idea?!


回答1:


You could try strsplit

msg <- "==================================================\n"
msg2 <- paste(msg, "Var:")
strsplit(msg2, "\n")[[1]]
# [1] "=================================================="
# [2] " Var:" 

This can also be used with noquote if you don't want quotes.

noquote(strsplit(msg2, "\n")[[1]])
# [1] ==================================================
# [2]  Var: 

This produces virtually the same result as if you were to use print with quote = FALSE

You can also define your own print method

print.myClass <- function(x, ...)  strsplit(x, "\n")[[1]]
class(msg2) <- "myClass"
print(msg2)
# [1] "=================================================="
# [2] " Var:"     


来源:https://stackoverflow.com/questions/26022378/r-new-line-in-paste-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!