2014-11-24 62 views
1

假设我有以下数据汇总数据:如何通过集群

library(data.table)  
set.seed(200) 
data <- data.table(income=runif(20, 1000,8000), gender=sample(0:1,20, T), asset=runif(20, 10000,80000),education=sample(1:4,20,T), cluster = sample(1:4, 20, T)) 

我的数据同时包含连续变量和分类变量。我想基于聚类变量汇总数据如下:

连续变量(收入和资产):使用mean,所以我申请

data[,lapply(.SD, mean), by = cluster, .SDcols = c(1,3)]

分类变量(性别和教育):我用

table(data[,gender, by = cluster])/rowSums(table(data[,gender, by = cluster])) 

table(data[,education, by = cluster])/rowSums(table(data[,education, by = cluster])) 

我不认为我的代码是有效的。

您能否给我建议如何处理这种情况?

回答

2

我会做这种方式:

data[, .N, by=.(gender, cluster)][, .(gender, ratio = N/sum(N)), by=cluster] 
data[, .N, by=.(education, cluster)][, .(education, ratio = N/sum(N)), by=cluster] 
1

你可以使用一个for循环的categorical变量

res <- list() 
for(i in c('gender', 'education')){ 
    res[[i]] <- prop.table(table(cbind(data[,'cluster', with=FALSE], 
          data[,i, with=FALSE])), margin=1) 
} 

res 

或者

lapply(data[,c('gender','education'), with=FALSE], function(x) 
     prop.table(table(cbind(data[,'cluster', with=FALSE],x)), margin=1))