简体   繁体   English

在 R (dplyr) 中保留单行组的同时计算分组平均值

[英]Compute grouped mean while retaining single-row group in R (dplyr)

I'm trying to compute mean + standard deviation for a dataset.我正在尝试计算数据集的均值 + 标准差。 I have a list of organizations, but one organization has just one single row for the column "cpue."我有一个组织列表,但一个组织只有一行“cpue”。 When I try to compute the grouped mean for each organization and another variable (scientific name), this organization is removed and yields a NA.当我尝试计算每个组织和另一个变量(学名)的分组平均值时,该组织被删除并产生 NA。 I would like to retain the single-group value however, and for it to be in the "mean" column so that I can plot it (without sd).但是,我想保留单组值,并将其放在“平均值”列中,以便我可以 plot 它(没有 sd)。 Is there a way to tell dplyr to retain groups with a single row when calculating the mean?有没有办法告诉 dplyr 在计算平均值时保留单行组? Data below:数据如下:

  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))

Any help would be much appreciated!任何帮助将非常感激!

We can create an if/else condition in sd to check for the number of rows ie if n() ==1 then return the 'cpue' or else compute the sd of 'cpue'我们可以在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')

-output -输出

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   

If the condition is based on the value of grouping variable 'organization', then create the condition in if/else by extracting the grouping variable with cur_group()如果条件基于分组变量“组织”的值,则通过使用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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM