I would like to know how to convert a variable in R to csv string.
> x = c(1:10)
> a = write.csv(x)
"","x"
"1",1
"2",2
"3",3
"4",4
"5",5
"6",6
"7",7
"8",8
"9",9
"10",10
> a
NULL
>
I want to have the CSV string in variable 'a'.
Thanks
I would like to know how to convert a variable in R to csv string.
> x = c(1:10)
> a = write.csv(x)
"","x"
"1",1
"2",2
"3",3
"4",4
"5",5
"6",6
"7",7
"8",8
"9",9
"10",10
> a
NULL
>
I want to have the CSV string in variable 'a'.
Thanks
Things can be so simple ....
> zz <- textConnection("foo1", "w")
> textConnectionValue(zz)
character(0)
> write.csv(x, zz)
> textConnectionValue(zz)
[1] "\"\",\"x\"" "\"1\",1" "\"2\",2" "\"3\",3" "\"4\",4"
[6] "\"5\",5" "\"6\",6" "\"7\",7" "\"8\",8" "\"9\",9"
[11] "\"10\",10"
>
textConnectionValue(zz). The value is already in variable foo1"1,2,3,4,5,6,7,8,9,10". For this you must pass a matrix rather than a vector to write.csv. Also, you want row.names=FALSE in write.csv. Unfortunately you cannot set col.names=FALSE and will either have to use write.table for this, or do foo1[2,] to skip the vector of column names.