quant quant - 1 year ago 77
R Question

How to write CSV with data.table counts per-variable?

Assuming I have a data table,

, with dimensions 1000x4, with column names
. If I do
I will get the counts for each value of the

What I would like to do, is to write all these values in a csv in one go,below each other, so I try

x <- c("x1","x2","x3","x4")
l_ply(x, function(x) {

but I get an error:

The items in the 'by' or 'keyby' list are length .... Each must be
same length as rows in x or number of rows returned by i ...

Any ideas ?

Answer Source

You have to use write.table(..., append=TRUE) because write.csv() wrapper doesn't pass it through.

Then (and if you don't want a per-variable header before each variable's section, use col.names=F ; see Write column header once only, when writing data with write.table(append=T) ):

x <- c("x1","x2","x3","x4")
td <- data.table(x1=sample.int(2,5,replace=T), x2=sample.int(2,5,replace=T), x3=sample.int(2,5,replace=T), x4=sample.int(2,5,replace=T))

l_ply(x, function(x) {
  write.table(td[,.N,by=x], file="test.csv", append=T, quote=F, row.names=F)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download