【问题标题】:How to print a vector in a sentence avoiding returning lines如何在句子中打印向量避免返回行
【发布时间】:2016-05-30 19:13:14
【问题描述】:

我想在句子中打印向量中的值。但是该向量包含 4 个元素,这导致答案分布在 4 行中。这就是我所拥有的:

  yo = c(2902, 2908, 2907, 2918)

  cat(paste('You have', yo, 'number of individuals per species\n', sep = ' '))

 You have 2902 number of individuals per species
 You have 2908 number of individuals per species
 You have 2907 number of individuals per species
 You have 2918 number of individuals per species

但我想要这样的东西

You have 2902, 2908, 2907 and 2918 number of individuals per species

可以这样做吗?此外,向量并不总是包含 4 个元素。如果我只有 3 或 10 个元素,它应该可以工作。

这不起作用:

  cat(sprintf('You have %s number of individuals per species\n',yo))


  cat(paste('You have', unlist(yo), 'number of individuals per species\n', sep = ' '))

【问题讨论】:

  • 试试toString(c(yo[-length(yo)], paste("and", yo[length(yo)])))。这使用牛津逗号。否则我会畏缩。
  • 为牛津逗号点赞!

标签: r vector printf cat


【解决方案1】:

您可以使用toString()paste() 来获取最后一部分。我还使用牛津逗号来衡量......

x <- toString(c(yo[-length(yo)], paste("and", yo[length(yo)])))
x
# [1] "2902, 2908, 2907, and 2918"

所以现在我们可以将x 插入到paste() 调用中。

paste("You have", x, "number of individuals per species")
# [1] "You have 2902, 2908, 2907, and 2918 number of individuals per species"

【讨论】:

    【解决方案2】:

    你必须 paste()collapse 选项:

    paste('You have',paste( yo[1:(length(yo)-1)], collapse= ', '), 'and', yo[length(yo)], 'number of individuals per species\n')
    You have 2902, 2908, 2907 and 2918 number of individuals per species
    

    【讨论】:

    • 能否在最后一个值前自动添加“and”而不是逗号?
    猜你喜欢
    • 2012-02-08
    • 1970-01-01
    • 2021-05-24
    • 2021-06-30
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    相关资源
    最近更新 更多