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

发布于 2024-10-07 15:23:43 字数 214 浏览 0 评论 0原文

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

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

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

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

Desired Output 

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

感谢您的帮助

How can I insert a comma between each element in paste command in R ?

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

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

Now I want to insert a comma between each element

Desired Output 

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

Thanks for your help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初雪 2024-10-14 15:23:43

我认为下面的两个命令之一应该适合您:

> 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 命令的输出作为 read.tablecol.names 参数。

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

I think one of the two commands below should work for you:

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

Update, based on comments:

There's no need to put commas "between" the vector elements. You can use the output of your paste command as the col.names arg to read.table.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文