问题
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