R-paste()函数中的新行 [英] R - new line in paste() function
问题描述
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...
msg <- "==================================================\n"
msg <- paste(msg, "Var:")
print(msg)
输出:
[1]"============================================= ======= \ n Var:"
[1] "==================================================\n Var:"
第二次尝试:paste0()
msg <- "==================================================\n"
msg <- paste0(msg, "Var:")
print(msg)
输出:
[1]"============================================= ======= \ n变量:"
[1] "==================================================\nVar:"
第三次尝试:sep
msg <- "=================================================="
msg <- paste(msg, "Var:", sep = "\n")
print(msg)
输出:
[1]"============================================= ======= \ n变量:"
[1] "==================================================\nVar:"
第4次尝试:sprintf
msg <- sprintf("==================================================\n")
msg <- paste(msg, "Var:")
print(msg)
输出:
[1]"============================================= ======= \ n变量:"
[1] "==================================================\nVar:"
我相信我已经尽力了...如果您有想法?!
I believe I've tried everything I could... If you have an idea?!
推荐答案
您可以尝试strsplit
msg <- "==================================================\n"
msg2 <- paste(msg, "Var:")
strsplit(msg2, "\n")[[1]]
# [1] "=================================================="
# [2] " Var:"
如果您不想使用引号,也可以将其与noquote
一起使用.
This can also be used with noquote
if you don't want quotes.
noquote(strsplit(msg2, "\n")[[1]])
# [1] ==================================================
# [2] Var:
这实际上产生与将print
与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:"
这篇关于R-paste()函数中的新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!