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]))
我不认为我的代码是有效的。
您能否给我建议如何处理这种情况?