Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

like image 229
Tony Avatar asked Dec 12 '10 02:12

Tony


1 Answers

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
like image 175
Joshua Ulrich Avatar answered Sep 20 '22 07:09

Joshua Ulrich