【问题标题】:n() not showing in the summarise() output from tidyvesre in Rn() 未显示在 R 中 tidyvesre 的 summarise() 输出中
【发布时间】:2020-09-13 18:44:18
【问题描述】:

我的代码在下面,我想知道为什么n = n() 的结果没有显示在最终输出中?

library(tidyverse)
hsb <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')

hsb %>% dplyr::select(math, sector) %>% group_by(sector) %>% 
summarise(across(.fns = list(mean=mean, sd=sd), n = n()))

【问题讨论】:

    标签: r dataframe dplyr tidyverse


    【解决方案1】:

    问题似乎与across 的右括号有关。我们希望n 成为单列,而不是针对每种情况重复,因此,我们可以关闭across 并单独使用n = n(),即在across 之外使用

    library(dplyr)
    hsb %>%
       dplyr::select(math, sector) %>%
       group_by(sector) %>% 
       summarise(across(.fns = list(mean=mean, sd=sd)), n = n(), .groups = 'drop')
    # A tibble: 2 x 4
    #  sector math_mean math_sd     n
    #   <int>     <dbl>   <dbl> <int>
    #1      0      11.4    7.08  3642
    #2      1      14.2    6.36  3543
    

    只是为了表明如果我们需要多个“n”列(不是真的需要)。在这里,我们select只有两列,其中一列是分组列,所以它只会返回一个'n'

    hsb %>%
      dplyr::select(math, sector) %>%
      group_by(sector) %>%
      summarise(across(.fns = list(mean = mean, sd = sd, 
             n = ~ n())), .groups = 'drop')=
    # A tibble: 2 x 4
    #  sector math_mean math_sd math_n
    #   <int>     <dbl>   <dbl>  <int>
    #1      0      11.4    7.08   3642
    #2      1      14.2    6.36   3543
    

    【讨论】:

      猜你喜欢
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2015-07-28
      • 1970-01-01
      • 2019-10-06
      相关资源
      最近更新 更多