R对矢量使用paste()时防止重复项目

Ali*_*Ali 5 r paste

考虑以下:

a = 1:10
paste("The list is:", a)
Run Code Online (Sandbox Code Playgroud)

结果将是:

 [1] "The list is: 1"  "The list is: 2"  "The list is: 3"  "The list is: 4" 
 [5] "The list is: 5"  "The list is: 6"  "The list is: 7"  "The list is: 8" 
 [9] "The list is: 9"  "The list is: 10"
Run Code Online (Sandbox Code Playgroud)

我通过以下方式解决了它:

paste("The list is:", paste(a, collapse=", "))
# "The list is: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10"
Run Code Online (Sandbox Code Playgroud)

有什么好主意吗?

Rei*_*son 9

我想这取决于你想要它.如果你将它粘在一起显示在R控制台中,比如作为注释或信息,那么cat()可以更直观地工作:

R> cat("The list is:", a, "\n")
The list is: 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)

要么

R> cat("The list is:", a, fill = TRUE)
The list is: 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)

如果你想将实际的字符串作为R对象,我认为你不会比paste()你所展示的习语简单得多.

  • 好主意.如果你想要字符串,你可以这样做:`capture.output(cat("list is:",a,fill = TRUE))` (2认同)