4

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

user1052080
  • 430
  • 5
  • 12
  • 2
    it isn't clear what you want. Perhaps you could show us what the end state would look like? – RJ- May 18 '12 at 09:36
  • 2
    Do you mean something like this? paste(x, collapse=",") – johannes May 18 '12 at 10:00
  • 1
    To add to RJ's question: what do you mean by "post to a remote server" ? Do you want to post a csv file? Or what? – Carl Witthoft May 18 '12 at 11:37
  • as said, I want to have the CSV string representation, which is printed to console by write.csv, stored in variable a. Does this make it clearer? – user1052080 May 18 '12 at 13:32
  • 1
    It's the reverse of http://stackoverflow.com/questions/3261066/in-r-how-can-i-parse-csv-data-from-a-character-vector-to-extract-a-data-frame ..... – user1052080 May 18 '12 at 13:38
  • well, found the answer. but can't self answer. well, I digged a bit more into textConnection and indeed, that's the answer ... it would be: 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" ... which is the csv text. – user1052080 May 18 '12 at 13:49

2 Answers2

5

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"
 > 
user1052080
  • 430
  • 5
  • 12
  • 1
    Even easier: You don't need `textConnectionValue(zz)`. The value is already in variable `foo1` – Carsten Nov 04 '14 at 00:04
  • 1
    A couple of clarifications: probably you want something like: `"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. –  Nov 19 '14 at 19:37
3

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"