【问题标题】:Count number of non-NA values by group按组计算非 NA 值的数量
【发布时间】:2017-06-10 17:44:42
【问题描述】:

例如,我有这个数据框(df):

Color    X1      X2    X3    X4
Red      1       1     0     2
Blue     0       NA    4     1 
Red      3       4     3     1
Green    2       2     1     0

我想创建一个函数,按组(即按“颜色”)计算“X2”中非NAs 的数量。我想在一个名为 newdf 的新数据框中输出这个函数。这就是我想要的输出:

Color    X2     
Red      2      
Blue     NA    
Green    1

到目前为止,我有这个代码:

Question <- function(Color){
  Result <-
    rowsum((df[c("X2")] > 0) + 0, df[["X2"]], na.rm = TRUE) 
  rowSums(Result)[[Color]]
  }
  Question("Red") 

这个函数给出的输出只是Question("Red")= 2,我想在一个新的数据框(newdf)中获得所有颜色的结果。有人能帮忙吗?谢谢!

【问题讨论】:

  • 你也可以有一个命名向量tapply(ifelse(is.na(df$X2), NA, 1), df$Color, FUN=sum)
  • 使用rowsum: rowsum(as.numeric(!is.na(dt$X2)), dt$Color)

标签: r na counting


【解决方案1】:

或者如果你想使用 data.table:

library(data.table)

dt[,sum(!is.na(X2)),by=.(Color)]

  Color V1
1:   Red  2
2:  Blue  0
3: Green  1

在 data.table 中使用 ifelse() 来获得蓝色而不是 0 的 NA 也很容易。请参阅:

dt[,ifelse(sum(!is.na(X2)==0),as.integer(NA),sum(!is.na(X2))),by=.(Color)]

   Color V1
1:   Red  2
2:  Blue NA
3: Green  1

数据:

 dt <- as.data.table(fread("Color    X1      X2    X3    X4
Red      1       1     0     2
Blue     0       NA    4     1 
Red      3       4     3     1
Green    2       2     1     0"))

【讨论】:

    【解决方案2】:
    library(dplyr)
    df1 <-  df %>%
               group_by(Color) %>%
               summarise(sum(!is.na(X2)))
    df1
    #  (chr)           (int)
    #1   Red               2
    #2  Blue               0
    #3 Green               1
    

    如果你真的想要NA 而不是0 那么

    df1[df1 ==0]<-NA
    

    【讨论】:

      【解决方案3】:

      使用基础 R,我们可以使用 aggregatena.action 参数作为 na.pass 以允许 NA

      aggregate(X2~Color, df, function(x) sum(!is.na(x)), na.action = na.pass)
      
      #  Color X2
      #1  Blue  0
      #2 Green  1
      #3   Red  2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-01
        • 1970-01-01
        • 2018-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多