【问题标题】:How can I print all the elements of a vector in a single string in R?如何在 R 中的单个字符串中打印向量的所有元素?
【发布时间】:2015-03-04 22:45:12
【问题描述】:

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

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

【问题讨论】:

    标签: r string-concatenation


    【解决方案1】:

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

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

    【讨论】:

    • collapse 而不是 sep 完成这项工作。谢谢!
    【解决方案2】:

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

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

    这给出了:

    The first three notes are:      do      re      mi
    

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

    【讨论】:

    • 还有,paste(..., collapse="\t")
    • 同样重要的是要注意cat确实适合向用户显示输出;该函数只会在不可见的情况下返回NULL。如果要捕获结果,则需要使用paste
    • @BrodieG 在这种情况下,就是paste(c("The first three notes are: ", notes,"\n"),collapse="\t")。谢谢!
    • @joran 非常正确。以下是如何捕获此场景的结果:result &lt;- paste(c("The first three notes are: ", notes,"\n"),collapse="\t")。谢谢!
    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2021-01-12
    • 2014-11-30
    • 2019-05-04
    • 2021-04-26
    相关资源
    最近更新 更多