【问题标题】:Compute grouped mean while retaining single-row group in R (dplyr)计算分组平均值,同时在 R (dplyr) 中保留单行组
【发布时间】:2021-04-07 23:06:40
【问题描述】:

我正在尝试计算数据集的均值 + 标准差。我有一个组织列表,但一个组织只有一行“cpue”。当我尝试计算每个组织和另一个变量(学名)的分组平均值时,该组织被删除并产生 NA。但是,我想保留单组值,并将其放在“平均值”列中,以便我可以绘制它(没有 sd)。有没有办法告诉 dplyr 在计算平均值时保留单行的组?数据如下:

  l<-  df<- data.frame(organization = c("A","B", "B", "A","B", "A", "C"),
             species= c("turtle", "shark", "turtle", "bird", "turtle", "shark", "bird"),
             cpue= c(1, 2, 1, 5, 6, 1, 3))

  l2<- l %>% 
       group_by( organization, species)%>%
       summarize(mean= mean(cpue),
                 sd=sd(cpue))

任何帮助将不胜感激!

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以在sd 中创建一个if/else 条件来检查行数,即if n() ==1 然后返回'cpue' 或else 计算'cpue' 的sd

    library(dplyr)
    l1 <-  l %>% 
       group_by( organization, species)%>%
       summarize(mean= mean(cpue),
                 sd= if(n() == 1) cpue else sd(cpue), .groups = 'drop')
    

    -输出

    l1
    # A tibble: 6 x 4
    #  organization species  mean    sd
    #* <chr>        <chr>   <dbl> <dbl>
    #1 A            bird      5    5   
    #2 A            shark     1    1   
    #3 A            turtle    1    1   
    #4 B            shark     2    2   
    #5 B            turtle    3.5  3.54
    #6 C            bird      3    3   
    

    如果条件基于分组变量'organization'的值,则通过提取cur_group()的分组变量在if/else中创建条件

    l %>% 
       group_by(organization, species) %>% 
       summarise(mean = mean(cpue),
           sd = if(cur_group()$organization == 'A') cpue else sd(cpue), 
                .groups = 'drop')
    

    【讨论】:

    • 这太棒了!但是由于某种原因,我一直在获得 NA。如果有多行,你也可以吗?例如,我正在尝试做同样的事情来提取一个因素但遇到麻烦:l1 %>% group_by(organization, species)%>% summarise(mean= mean(cpue), sd= if(organization== "A") cpue else sd(cpue), .groups = 'drop') –
    • @AlyssaC if/else 在输入长度为 1 时起作用。即 n() ==1 返回单个 TRUE 或 FALSE。如果您需要针对其他情况执行此操作,请使用 ifelsecase_when 即我看到您正在使用分组列上的条件。所以,你可能需要if(first(organization) == "A") cpue else sd(cpue), .groups = 'drop')
    • @AlyssaC 我认为cur_group 会更好。我更新了
    猜你喜欢
    • 2021-05-23
    • 2018-03-21
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    相关资源
    最近更新 更多