在R中分组数据的summary()中的slice()之后,mean()不起作用
我对我的数据进行了分组,我想在忽略组中的N个最低值后得到平均值。我的代码与下面的代码类似:在R中分组数据的summary()中的slice()之后,mean()不起作用,r,if-statement,dplyr,grouping,slice,R,If Statement,Dplyr,Grouping,Slice,我对我的数据进行了分组,我想在忽略组中的N个最低值后得到平均值。我的代码与下面的代码类似: mtcars %>% group_by(gear) %>% arrange(desc(wt)) %>% summarise( n = n(), Drop2 = if_else(n() >= 5, slice(1:(n() - 2)) %>% mean(wt), #omit the two lowest val
mtcars %>%
group_by(gear) %>%
arrange(desc(wt)) %>%
summarise(
n = n(),
Drop2 = if_else(n() >= 5,
slice(1:(n() - 2)) %>% mean(wt), #omit the two lowest value of "wt" then get the mean
NA),
Drop1 = if_else(n() >= 3 & n() < 5,
slice(1:(n() - 1)) %>% mean(wt), #omit the lowest value of "wt" then get the mean
NA),
Weight = mean(wt)
)
当Drop2中gear=3的结果很容易是NA时,我不太清楚为什么会出现这个错误。slice的第一个参数是
。data
,它主要用于对行进行子集设置。这里的切片(1:(n()-1))
没有.data
输入,只指定索引。使用slice
作为链中的独立步骤更合适。另外,在内执行切片
摘要
,然后在内执行if_else
会使它变得复杂。根据代码,我们只需要对“wt”列进行子集,这可以通过直接在该列上建立索引来完成
library(dplyr)
mtcars %>%
group_by(gear) %>%
arrange(desc(wt)) %>%
summarise(n = n(),
Drop2 = if_else(n() >= 5, mean(wt[1:(n() - 2)],
na.rm = TRUE), NA_real_),
Drop1 = if_else(n() >=3 & n() < 5, mean(wt[1:(n() - 1)],
na.rm = TRUE), NA_real_),
Weight = mean(wt))
使用
排序
和尾部
mtcars %>%
group_by(gear) %>%
summarise(n = n(), Weight_top = mean(tail(sort(wt), -2)),
Weight = mean(wt))
# A tibble: 3 x 4
# gear n Weight_top Weight
#* <dbl> <int> <dbl> <dbl>
#1 3 15 4.05 3.89
#2 4 12 2.80 2.62
#3 5 5 3.17 2.63
mtcars%>%
分组依据(档位)%>%
总结(n=n(),权重_top=平均值(尾部(排序(wt),-2)),
重量=平均值(重量))
#一个tibble:3x4
#齿轮n重量\顶部重量
#*
#1 3 15 4.05 3.89
#2 4 12 2.80 2.62
#3 5 5 3.17 2.63
太棒了!感谢您的清晰解释和建议的替代解决方案。
# A tibble: 3 x 5
# gear n Drop2 Drop1 Weight
# <dbl> <int> <dbl> <dbl> <dbl>
#1 3 15 4.05 NA 3.89
#2 4 12 2.80 NA 2.62
#3 5 5 3.17 NA 2.63
mtcars %>%
group_by(gear) %>%
arrange(desc(wt)) %>%
summarise(n = n(), Drop2 = if(n() >= 5) mean(wt[1:(n() - 2)]) else NA_real_)
mtcars %>%
group_by(gear) %>%
summarise(n = n(), Weight_top = mean(tail(sort(wt), -2)),
Weight = mean(wt))
# A tibble: 3 x 4
# gear n Weight_top Weight
#* <dbl> <int> <dbl> <dbl>
#1 3 15 4.05 3.89
#2 4 12 2.80 2.62
#3 5 5 3.17 2.63