4

我想知道如何将 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
> 

我想在变量“a”中有 CSV 字符串。

谢谢

4

2 回答 2

5

事情可以这么简单......

 > 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"
 > 
于 2012-05-19T08:45:45.633 回答
3

这是一个替代方案,甚至更简单:

foo2 <- capture.output(write.csv(matrix(1:6,nrow=2), stdout(), row.names=F)) 
foo2
## "\"V1\",\"V2\",\"V3\"" "1,3,5"                "2,4,6" 

可能你想要的是:

foo2[-1,]    
## "\"V1\",\"V2\",\"V3\"" "1,3,5"                "2,4,6" 
于 2014-11-19T19:41:05.747 回答