user3580643
user3580643

Reputation: 111

Using write.table to write rows row-by-row to a CSV in R, as you would in Python's writerows

How to write to a csv file in R, in a similar way to what I did in Python?

In Python, I did this:

import os
import csv
import numpy as np

#sample data
x = np.asarray((1,2,3))
y = np.asarray((4,5,6))

filename = os.path.normpath("output_py.csv")
f = open(filename, "wb")
writer = csv.writer(f,delimiter=',')

writer.writerow(x)
writer.writerow(y)

f.close() 

writer.writerow(array) works well because I don't need to replicate parameters when writing. All I need to do is specify the array to write to.

I would like to do the same in R. Here is what I have done thus far:

#sample data
x  <-  as.matrix(c(1,2,3))
y  <-  as.matrix(c(4,5,6))

filepath  <- file.path("output_R.csv") 
fileConn <- file(filepath)

#To write over previous files - only for first line 
write.table(as.matrix(t(x)), sep=",", filepath, col.names=FALSE, row.names=FALSE)

#Thereafter append
write.table(as.matrix(t(y)), sep=",", filepath, col.names=FALSE, row.names=FALSE, append=TRUE)

close(fileConn)

Both methods produce the correct output,

1,2,3
4,5,6

but the problem is that each time I use write.table I need to replicate the parameters.

How to write rows without having to replicate parameters each time?

p.s. Any other suggestions for code optimisation will be appreciated.

Upvotes: 2

Views: 1739

Answers (1)

shadow
shadow

Reputation: 22293

Just write your own function write.row, that uses the parameters that you would like as standards, e.g.

write.row <- function(x, file = filepath, append = TRUE, quote = TRUE, sep=",", 
                      eol = "\n", na = "NA", dec = ".", row.names = FALSE, col.names = FALSE, 
                      qmethod = c("escape", "double"), fileEncoding = ""){
  write.table(as.matrix(t(x)), file, append , quote, sep, 
              eol, na, dec, row.names, col.names, 
              qmethod, fileEncoding)
}
write.row(x, append=FALSE)
write.row(y)

In this case, I assumed that you want to call this function many times and would like to use append=TRUE as the default and change it for the first row. Otherwise just set the default to FALSE.

Upvotes: 1

Related Questions