How to export a datatable for each key?

梦想与她 提交于 2019-12-10 22:36:26

问题


Let's consider the datatable :

> dt=data.table(v1=1:10, v2=c(rep("a",5),rep("b",5)))
    v1 v2
 1:  1  a
 2:  2  a
 3:  3  a
 4:  4  a
 5:  5  a
 6:  6  b
 7:  7  b
 8:  8  b
 9:  9  b
10: 10  b

How would I do to export dt into as many files as there are v2 naming the files after them ? Meaning one file named a containing 1 2 3 4 5 and one file named b containing 6 7 8 9 10.

I tried : dt[, fwrite(.(v1), v2), by=v2] but to no avail.

Alternatively how would I export the dt into one single file formated as following :

1 2 3 4 5
6 7 8 9 10

回答1:


Taken from my other answer here.

dt[, fwrite(.SD, paste0(.BY,".csv")), by=v2, .SDcols="v1"]

If you group by multiple columns, just wrap .BY with paste(., collapse="_").




回答2:


How about:

Labels = unique(dt$v2)
for(lab in Labels) {
    FileName = paste("DT_", lab, ".csv", sep="")
    write.csv(dt[dt$v2 == lab, ],  FileName)
}



回答3:


We can also split the 'dt' into list based on the 'v2' and then use fwrite

lst <- split(dt, dt$v2)
invisible(lapply(names(lst), function(nm) fwrite(lst[[nm]], paste0("DT_", nm, ".csv"))))


来源:https://stackoverflow.com/questions/40966634/how-to-export-a-datatable-for-each-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!