Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

csv

This is a very simple issue and I'm surprised that there are no examples online.

I have a vector:

vector <- c(1,1,1,1,1)

I would like to write this as a csv as a simple row:

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

When I open up the file I've just written, the csv is written as a column of values. It's as if R decided to put in newlines after each number 1.

Forgive me for being ignorant, but I always assumed that the point of having comma-separated-values was to express a sequence from left to right, of values, separated by commas. Sort of like I just did; in a sense mimicking the syntax of written word. Why does R cling so desperately to the column format when a csv so clearly should be a row?

All linguistic philosophy aside, I have tried to use the transpose function. I've dug through the documentation. Please help! Thanks.

like image 267
Didi Bui Avatar asked Dec 01 '13 04:12

Didi Bui


2 Answers

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")
like image 157
user8683648 Avatar answered Sep 30 '22 16:09

user8683648


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

like image 37
tumultous_rooster Avatar answered Sep 30 '22 16:09

tumultous_rooster