【问题标题】:Calculating the proportion per subgroup with data.table [duplicate]使用 data.table 计算每个子组的比例
【发布时间】:2018-09-24 13:41:09
【问题描述】:

对于下面的简单数据集;

   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 我最终用你的方法得到了 6 行。
  • @AndreElrico 这很正常,这只是为了获得所需的输出而遵循(或不遵循)的路径;-)

标签: r data.table mean


【解决方案1】:

使用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). 这可能是因为我的变量中的 1 个是一个因素吗?
  • 在运行我的解决方案之前,请确保您的 data.table 中没有 sum 或 prop 列。然后再试一次,我想它会起作用的。
  • 我似乎无法让它工作。至于你的评论;那里不应该有 sum 列。对于道具列,您的意思是浮点数/双精度数?我正在处理非常大的数据集。需要检查、更改或子集是不可行的。
  • dput 原始数据集的子集。我将能够弄清楚出了什么问题。像这样很难。解决方案适用于您提供的数据
猜你喜欢
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 2015-09-12
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多