使用data.table计算每个子组的比例

3
以下是简单数据集的内容;
   row  country year
     1  NLD     2005
     2  NLD     2005       
     3  BLG     2006
     4  BLG     2005
     5  GER     2005
     6  NLD     2007
     7  NLD     2005
     8  NLD     2008

以下代码:
df[, .N, by = list(country, year)][,prop := N/sum(N)]

给出了相对于总观测量的观测比例。然而,我想要衡量每个国家的比例。我应该如何修改此代码以给出正确的比例?

期望输出:

   row  country year  prop
     1  NLD     2005   0.6
     2  NLD     2005   0.6    
     3  BLG     2006   0.5
     4  BLG     2005   0.5
     5  GER     2005   1
     6  NLD     2007   0.2
     7  NLD     2005   0.6  
     8  NLD     2008   0.2

df[, {ty <- table(year); .(prop=as.vector(ty)/sum(ty), year=names(ty))}, by=country] - Cath
@Cath,使用您的方法,我最终得到了6行。 - Andre Elrico
@AndreElrico 这很正常,这只是一个供大家遵循(或不遵循)以获得所需输出的示例;-) - Cath
1个回答

5

使用 data.table

df <- read.table(header = T, text = "row  country year
     1  NLD     2005
                 2  NLD     2005       
                 3  BLG     2006
                 4  BLG     2005
                 5  GER     2005
                 6  NLD     2007
                 7  NLD     2005
                 8  NLD     2008")

setDT(df)[, sum := .N, by = country][, prop := .N, by = c("country", "year")][, prop := prop/sum][, sum := NULL]


    row country year prop
1:   1     NLD 2005  0.6
2:   2     NLD 2005  0.6
3:   3     BLG 2006  0.5
4:   4     BLG 2005  0.5
5:   5     GER 2005  1.0
6:   6     NLD 2007  0.2
7:   7     NLD 2005  0.6
8:   8     NLD 2008  0.2

非常感谢!我在实际数据集中遇到了以下错误:Error in [.data.table(setDT(ES2)[, :=(sum, .N), by = m1a], , :=(prop, : Type of RHS (integer) must match LHS (double). To check and coerce would impact performance too much for the fastest cases. Either change the type of the target column, or coerce the RHS of := yourself (e.g. by using 1L instead of 1). 这可能是由于我的某个变量是因子变量导致的吗? - Tom
在运行我的解决方案之前,请确保您的data.table中没有sum或prop列。然后再试一次,我猜应该会成功。 - sm925
我似乎无法让它工作。至于您的评论; 那里不应该有sum列。你所说的prop列是指像float / double这样的东西吗?我正在处理非常大的数据集。需要检查,更改或子集可能不是真正可行的。 - Tom
将您原始数据集的“dput”子集提供给我。我将能够找出问题所在。这样很难解决。解决方案适用于您提供的数据。 - sm925

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接