如何在R中的单个字符串中打印矢量的所有元素?

时间:2015-03-04 22:45:13

标签: r string-concatenation

有时我想在一个字符串中打印矢量中的所有元素,但它仍然会分别打印元素:

notes <- c("do","re","mi")
print(paste("The first three notes are: ", notes,sep="\t"))

给出了:

[1] "The first three notes are: \tdo" "The first three notes are: \tre"
[3] "The first three notes are: \tmi"

我真正想要的是:

The first three notes are:      do      re      mi

2 个答案:

答案 0 :(得分:7)

最简单的方法可能是使用一个c函数合并您的消息和数据:

paste(c("The first three notes are: ", notes), collapse=" ")
### [1] "The first three notes are:  do re mi"

答案 1 :(得分:1)

cat函数con cat 枚举向量的元素并打印出来:

cat("The first three notes are: ", notes,"\n",sep="\t")

给出了:

The first three notes are:      do      re      mi

sep参数允许您指定分隔字符(例如,此处为\t选项卡)。此外,如果您之后有任何其他输出或命令提示符,也建议在末尾添加换行符(即\n)。