[英]Compute grouped mean while retaining single-row group in R (dplyr)
我正在尝试计算数据集的均值 + 标准差。 我有一个组织列表,但一个组织只有一行“cpue”。 当我尝试计算每个组织和另一个变量(学名)的分组平均值时,该组织被删除并产生 NA。 但是,我想保留单组值,并将其放在“平均值”列中,以便我可以 plot 它(没有 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))
任何帮助将非常感激!
我们可以在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
如果条件基于分组变量“组织”的值,则通过使用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.