【问题标题】:"Weighted" counts at each combination of factor levels每个因子水平组合的“加权”计数
【发布时间】:2020-03-21 11:36:27
【问题描述】:

我有以下:

> df=data.frame(from = c("x","y","x","z"), to=c("w","x","w","y"),weight=c(1,1,3,4))
> df
  from to weight
1    x  w      1
2    y  x      1
3    x  w      3
4    z  y      4

如果我想计算列from的元素出现在中的次数,我需要使用:

> table(df$from)
x y z 
2 1 1 

这不是加权和。无论如何,我怎么能考虑weight这个专栏?例如。在我的例子中,正确答案应该是:

x y z 
4 1 4 

【问题讨论】:

    标签: dataframe dataframe r dataframe data-manipulation


    【解决方案1】:

    您可以使用tapply 并为from 中的每个唯一值计算sum

    tapply(df$weight, df$from, sum)
    
    #x y z 
    #4 1 4 
    

    【讨论】:

      【解决方案2】:

      我们可以从dplyr使用count

      library(dplyr)
      df %>% 
          count(from, wt = weight)
      #  from n
      #1    x 4
      #2    y 1
      #3    z 4
      

      在base R,我们可以使用xtabs

      xtabs(weight~ from, df)
      #from
      #x y z 
      #4 1 4 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-10
        • 1970-01-01
        • 2019-01-22
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        相关资源
        最近更新 更多