Using column names when adding data to write.table

I look at some data and add it to the csv file. I want the column names to be at the top of the file once, and then when it is looped so as not to repeat the column names in the middle of the file.

If I do col.names=T , it repeats, including the column names for each new loop. If I have col.names=F , there are no column names at all.

How do I do this most efficiently? I feel that this is such a general case that there should be a way to do this without writing code, especially to handle it.

 write.table(dd, "data.csv", append=TRUE, col.names=T) 
+6
source share
2 answers

You may also see a problem with line names that are identical, because write.table does not allow identical line names when adding. You can try. In the first write to the file, try write.table with only row.names = FALSE . Then, starting with the second entry in the file, use both col.names = FALSE and row.names = FALSE

Here is the first entry in the file

 > d1 <- data.frame(A = 1:5, B = 1:5) ## example data > write.table(d1, "file.txt", row.names = FALSE) 

We can verify this with read.table("file.txt", header = TRUE) . Then we can add the same data frame to this file using

 > write.table(d1, "file.txt", row.names = FALSE, col.names = FALSE, append = TRUE) 

And again, we can verify this with read.table("file.txt", header = TRUE)

So, if you have a list of data frames, say dlst , your code snippet that adds data frames together may look something like

 > dlst <- rep(list(d1), 3) ## list of example data > write.table(dlst[1], "file.txt", row.names = FALSE) > invisible(lapply(dlst[-1], write.table, "file.txt", row.names = FALSE, col.names = FALSE, append = TRUE)) 

But, as @MrFlick suggests, it would be much better to add data frames to R and then send them to a file once. This will fix many possible errors / problems that may occur when writing to a file. If the data is in the list, this can be done using

 > dc <- do.call(rbind, dlst) > write.table(dc, "file.txt") 
+3
source

See ?file.exists .

 write.table(dd, "data.csv", append=TRUE, col.names=!file.exists("data.csv")) 

This way, column names are only recorded if you are not adding a file that already exists.

+10
source

Source: https://habr.com/ru/post/971442/


All Articles