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

How can I print all the elements of a vector in a single string in R?

有时我想在单个字符串中打印向量中的所有元素,但它仍然单独打印元素:

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

cat 函数都 concat 生成向量的元素并打印它们:

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

给出:

The first three notes are:      do      re      mi

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

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

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