我只尝试在列B == 1时对每个组中的列A求和,并将其变异为sum_A列。但是在sum_A列中显示了NA,其中B ==0。如何克服这个问题?非常感谢!
我的代码输出:
所需的输出:
我的代码:
library(dplyr)
df <- structure(list(A = c(5.1, 4.9, 4.7, 4.6, 5, 5.4, 4.6, 5, 4.4,
4.9), B = c(1, 1, 0, 0, 0, 1, 1, 0, 1, 1), group = c(1L, 1L,
2L, 2L, 3L, 3L, 4L, 4L, 5L, 5L)), row.names = c(NA, -10L), class = "data.frame")
df <- df %>%
group_by(group) %>%
mutate(sum_A = case_when(B==1 ~ sum(A)))
我们可以fill
在'sum_A'中使用具有非NA元素的组,然后将NA替换为0(replace_na
)
library(dplyr)
library(tidyr)
df %>%
group_by(group) %>%
mutate(sum_A = case_when(B==1 ~ sum(A))) %>%
fill(sum_A, .direction = 'downup') %>%
ungroup %>%
mutate(sum_A = replace_na(sum_A, 0))
-输出
# A tibble: 10 x 4
# A B group sum_A
# <dbl> <dbl> <int> <dbl>
# 1 5.1 1 1 10
# 2 4.9 1 1 10
# 3 4.7 0 2 0
# 4 4.6 0 2 0
# 5 5 0 3 10.4
# 6 5.4 1 3 10.4
# 7 4.6 1 4 9.6
# 8 5 0 4 9.6
# 9 4.4 1 5 9.3
#10 4.9 1 5 9.3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句