r - using column names when appending data in write.table -
i looping through data, , appending csv file. want have column names on top of file once, , loops not repeat column names in middle of file.
if col.names=t, repeats including column names each new loop. if have col.names=f, there no column names @ all.
how do efficiently? feel such common case there must way it, without writing code handle it.
write.table(dd, "data.csv", append=true, col.names=t)
you may or may not see problem row names being identical, write.table not allow identical row names when appending. give try. in first write file, try write.table row.names = false only. then, starting second write file, use both col.names = false , row.names = false
here's first write file
> d1 <- data.frame(a = 1:5, b = 1:5) ## example data > write.table(d1, "file.txt", row.names = false) we can check read.table("file.txt", header = true). can append same data frame file
> write.table(d1, "file.txt", row.names = false, col.names = false, append = true) and again can check read.table("file.txt", header = true)
so, if have list of data frames, dlst, code chunk appends data frames might 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 @mrflick suggests, better append data frames in r, , send them file once. eliminate many possible errors/problems occur while writing file. if data in list, done
> dc <- do.call(rbind, dlst) > write.table(dc, "file.txt")
Comments
Post a Comment