简体   繁体   中英

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?

ps Any other suggestions for code optimisation will be appreciated.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM