我只想在满足条件的情况下应用函数complete()
。
例如
library(dplyr)
library(tidyr)
df <- tibble(
group = c(1,1,1,1,2,2,3,3,3),
value1 = c(0,1,2,3,0,1,0,1,2),
value2 = c(2,4,6,1,2,3,7,8,9),
status = c(1,1,1,1,0,0,1,1,1)
)
df %>% complete(group, value1)
在上面的示例中,我想做最后一步,但是在变量“状态”取值为1的情况下,仅由complete()
执行扩展。任何人都有指针吗?谢谢!
答案 0 :(得分:1)
肯定有一个更优雅的解决方案,但是我相信这会起作用:
数据:
library(dplyr)
library(tidyr)
df <- tibble(
group = c(1,1,1,1,2,2,3,3,3),
value1 = c(0,1,2,3,0,1,0,1,2),
value2 = c(2,4,6,1,2,3,7,8,9),
status = c(1,1,1,1,0,0,1,1,1)
)
代码:
df %>%
filter(status == 1) %>%
complete(group, value1) %>%
bind_rows(subset(df, status == 0))