【问题标题】:Summarise_if count for all variable.names [duplicate]Summarise_if 所有变量名的计数[重复]
【发布时间】:2018-09-03 12:36:46
【问题描述】:

我正在尝试为所有按类变量分组的列获取meancount,但对于计数 - n()(第三条语句)我收到错误

错误:不应直接调用此函数

Class <- c("A","A","A","A","B","B","B","C","C","C","C","C","C")
A<-c(23,33,NA,56,22,34,34,45,65,5,57,75,57)
D<-c(2,133,5,60,23,312,341,25,75,NA,3,9,21)
M<-c(34,35,67,325,46,56,547,47,67,67,68,3,12)

df <- data.frame(Class,A,D,M)
library(dplyr)

system.time(df_sum <- df %>% group_by(Class) %>% summarise_if(is.numeric, sum , na.rm=T))
system.time(df_mean <- df %>% group_by(Class) %>% summarise_if(is.numeric, mean , na.rm=T))

system.time(df_count <- df %>% group_by(Class) %>% summarise_if(is.numeric, n() , na.rm=T))

请建议我对上述声明进行任何修改。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    要获取每个数字列中非 NA 值的数量,您可以使用:

    library(dplyr)
    
    df %>%
      group_by(Class) %>%
      summarise_if(is.numeric,
                   function(x) sum(!is.na(x)))
    
    #output
    # A tibble: 3 x 4
      Class     A     D     M
      <fct> <int> <int> <int>
    1 A         3     4     4
    2 B         3     3     3
    3 C         6     5     6
    

    n() 函数没有那么灵活,它没有 na.rm 参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 2022-01-15
      • 2019-01-28
      相关资源
      最近更新 更多