I would like to know how to convert a variable in R to csv string.
我想知道如何将R中的变量转换成csv字符串。
> 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'.
我想用变量'a'中的CSV字符串。
Thanks
谢谢
2 个解决方案
#1
2
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"
>
#2
1
Here's an alternative, even easier:
这里有一个更简单的选择:
foo2 <- capture.output(write.csv(matrix(1:6,nrow=2), stdout(), row.names=F))
foo2
## "\"V1\",\"V2\",\"V3\"" "1,3,5" "2,4,6"
Probably what you want is:
也许你想要的是:
foo2[-1,]
## "\"V1\",\"V2\",\"V3\"" "1,3,5" "2,4,6"
#1
2
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"
>
#2
1
Here's an alternative, even easier:
这里有一个更简单的选择:
foo2 <- capture.output(write.csv(matrix(1:6,nrow=2), stdout(), row.names=F))
foo2
## "\"V1\",\"V2\",\"V3\"" "1,3,5" "2,4,6"
Probably what you want is:
也许你想要的是:
foo2[-1,]
## "\"V1\",\"V2\",\"V3\"" "1,3,5" "2,4,6"