我正在尝试使用分组依据和汇总功能来计算非零值的均值。
示例:=
Group Val
A 3
A 0
A 3
B 1
B 0
B 1
test %>%
group_by(Group) %>%
summarise(Mean = mean(test$Val[ Val != 0 ])
所需的输出应为
Group Mean
A 3
B 1
相反,我得到
Group Mean
A 2
B 0.66
答案 0 :(得分:0)
要回答您的两个问题,我们需要创建一个新的示例数据:
set.seed(123)
test <- data.frame(Group = rep(c("A", "B"), 5),
Val = replicate(10, sample(c(-3:3), 1, replace = TRUE)))
如@Jon Spring所建议的那样,您可以通过过滤来获得每个不包含零的组的平均值:
require(tidyverse)
test %>%
group_by(Group) %>%
filter(Val != 0) %>%
summarise(Mean = mean(Val))
要获得每个组和正负号的均值不为零-我们可以为正负号和group_by
组和正负号创建一个新变量:
test %>%
mutate(sign = ifelse(Val > 0, "positive", "negative")) %>%
group_by(Group, sign) %>%
filter(Val != 0) %>%
summarise(Mean = mean(Val))
结果:
Group sign Mean
<fct> <chr> <dbl>
1 A negative -1
2 A positive 3
3 B negative -3
4 B positive 2.67