如何在R中的粘贴命令中的每个元素之间插入逗号?

paste ("X",1:5,sep="")

"X1" "X2" "X3" "X4" "X5"

现在我想在每个元素之间插入一个逗号
Desired Output

"X1","X2","X3","X4","X5"

谢谢你的帮助

最佳答案

我认为以下两个命令之一应该为您工作:

> paste ("X",1:5,sep="", collapse=",")
[1] "X1,X2,X3,X4,X5"
> paste ("'","X",1:5,"'",sep="", collapse=",")
[1] "'X1','X2','X3','X4','X5'"

根据评论更新:

无需在向量元素之间添加逗号。您可以将paste命令的输出用作col.namesread.table arg。
lines <-
"0 1 2 3 4
 5 6 7 8 9"

con <- textConnection(lines)
cnames <- paste("X",1:5,sep="")
x <- read.table(con, col.names=cnames)
close(con)
x
#   X1 X2 X3 X4 X5
# 1  0  1  2  3  4
# 2  5  6  7  8  9

10-06 01:38