如何使用data.table的每变量计数写入CSV?

时间:2016-11-18 10:57:51

标签: r file-io count data.table plyr

假设我有一个数据表for(int i = 0; i < lQuestModels.size(); i++){ StartMyFragment start_survey=new StartMyFragment(); Bundle bundle = new Bundle(); bundle.putString("survey_id", "111"); bundle.putString("survey_name", "testing"); bundle.putString("survey_desc", "Yes done"); bundle.putString("survey_no_of_question", "5"); bundle.putString("jListString", lQuestModels.get(i).toString()); start_survey.setArguments(bundle); fragmentManager = getSupportFragmentManager(); fragmentManager.popBackStack(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.welcomeSurveyLayout,start_survey); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } ,其维度为1000x4,列名为td。如果我x1,x2,x3,x4,我将获得td[,.N,x1]变量的每个值的计数。

我想做的是将所有这些值一次性写入csv,低于对方,所以我尝试

x1

但是我收到了错误:

  

&#39; by&#39;中的项目或者&#39; keyby&#39;列表是长度....每个必须   与x中的行数相同的长度或i ...返回的行数

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您必须使用write.table(..., append=TRUE),因为write.csv()包装器没有通过它(!)

然后(如果您不想在每个变量的部分之前使用每变量标题,请使用col.names=F;请参阅Write column header once only, when writing data with write.table(append=T)):

require(data.table)
require(plyr)
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)
})

答案 1 :(得分:0)

我们可以使用for循环

for(val in x) {
     write.table(td[, .N, by = c(val)], file = "test.csv", append=TRUE)
 }

答案 2 :(得分:0)

您还可以使用data.table中的rbindlist:

write.csv(
    file = "./tmp.csv",
    x = rbindlist(lapply(x,function(y){
        dt[,.N,by = y]
    }))
)