6

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

6
  • 2
    it isn't clear what you want. Perhaps you could show us what the end state would look like? Commented May 18, 2012 at 9:36
  • 2
    Do you mean something like this? paste(x, collapse=",") Commented May 18, 2012 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? Commented May 18, 2012 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? Commented May 18, 2012 at 13:32
  • 1
    It's the reverse of stackoverflow.com/questions/3261066/… ..... Commented May 18, 2012 at 13:38

2 Answers 2

6

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"
 > 
Sign up to request clarification or add additional context in comments.

2 Comments

Even easier: You don't need textConnectionValue(zz). The value is already in variable foo1
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.
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" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.