How do I write a csv file in R, where my input is written to the file as row?

I tried with this:

write.csv(rbind(vector), file ="myfile.csv", row.names=FALSE)

Output is getting written column wise, but, with column names.

This one seems to be better:

write.table(rbind(vector), file = "myfile.csv", row.names =FALSE, col.names = FALSE,sep = ",")

Now, the output is being printed as:

1   1   1   1   1

in the .csv file, without column names.


write.csv is designed for matrices, and R treats a single vector as a matrix with a single column. Try making it into a matrix with one row and multiple columns and it should work as you expect.

write.csv(matrix(vector, nrow=1), file ="myfile.csv", row.names=FALSE)

Not sure what you tried with the transpose function, but that should work too.

write.csv(t(vector), file ="myfile.csv", row.names=FALSE)

Here's what I did:

cat("myVar <- c(",file="myVars.r.txt", append=TRUE);

cat( myVar,       file="myVars.r.txt", append=TRUE, sep=", ");

cat(")\n",        file="myVars.r.txt", append=TRUE);

this generates a text file that can immediately be re-loaded into R another day using:

source("myVars.r.txt")

Following up on what @Matt said, if you want a csv, try eol=",".

Tags:

Csv

R