如何在避免返回行的句子中打印向量

How to print a vector in a sentence avoiding returning lines

我想在句子中打印向量中的值。但是向量包含 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 = ' '))

您必须 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

您可以使用 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"