由data.table中的group by Porportions

时间:2016-08-26 00:27:48

标签: r data.table

R一段时间后,我觉得我在制作非常笨拙的代码,以便在data.table中获取基本的摘要统计信息。

我正在做的是找出以物种为条件的健康状况良好/不良的个体比例。

# Some data 
n = 300
set.seed(2)
dt <- data.table(type = sample(x = c("Dog", "Cat", "Horse"), size = n, replace = TRUE),
                 health = sample(x = c("Good", "Bad"), size = n, replace = TRUE))

# Making the table. In a clumsy manner?
dt.fr <- dt[, .N, .(type, health)][, perc.type := N/sum(N)*100, 
                                   by = type][order(type, health)]
dt.fr

    type health  N perc.type
1:   Cat    Bad 38  44.70588
2:   Cat   Good 47  55.29412
3:   Dog    Bad 56  50.90909
4:   Dog   Good 54  49.09091
5: Horse    Bad 61  58.09524
6: Horse   Good 44  41.90476

如何使用更优雅的代码生成上表?

0 个答案:

没有答案