0

My intention is to format a simple matrix in csv format. As I need to further process the formatted lines, I don't want to write the formatted string to a file.

I already tried using textConnection, which seems to be the right approach.

m<-matrix(c(1,2,3,4), nrow=2)
result<-write.csv(m, file=textConnection(csvData), row.names=FALSE, col.names=FALSE)

I'm expecting csvData to contain the contents of the formatted csv (file) as a vector containing the lines.

I get the error:

Error in textConnection(csvData) : invalid 'text' argument

What is the proper usage of textConnection?

Revised question

After some trying and cleaning all variables I ended up with

rm(list = ls())
m<-matrix(c(1,2,3,4), nrow=2)
result<-write.csv(m, file=textConnection("csvData", "w"), row.names=FALSE, col.names=FALSE)

This produces at least no errors, but I ended with a warning that col.names are ignored. The content of csvData is also not what I expected

> csvData
[1] "\"V1\",\"V2\"" "1,3"           "2,4"  

How to remove the header?

My solution

After trying I found, that write.csv should be replaced by write.table.

rm(list = ls())
m<-matrix(c(1,2,3,4), nrow=2)
result<-write.table(m, file=textConnection("csvData", "w"), row.names=FALSE, col.names=FALSE, sep=";")
3
  • 1
    Does write.csv(m, "mymatrix.csv") generate the desired output? Check it via read.csv("mymatrix.csv"). Commented Dec 8, 2017 at 10:24
  • Yes, but I don't want the header and row names in the output file. I thought write.csv(m, "mymatrix.csv", row.names=FALSE, col.names=FALSE) should do it, right? Commented Dec 8, 2017 at 10:27
  • But col.names is ignored, so why write.csv has a paramater col.names, which is just ignored? Commented Dec 8, 2017 at 10:28

1 Answer 1

1

Try write.csv() from MASS

MASS::write.matrix(m, file = textConnection("csvData", "w"), sep = ";")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I don't want to write to a file. I wanted to write to vector containing the lines of the file. I already found a solution. Thanks for your efforts.
Hilarious. Many thanks, even though I already found a working solution for myself.

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.