我有按“id”分组的数据,以及一个可以是“yes”、“no”或NA
的列“x”。
我只想保留那些“id”,其中“x”(1) 包含两个"is",(2) "is"之间没有“否”值。 NA
介于两个"is"之间即可。
一些玩具数据:
data <- data.frame(id = c(1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5),
x = c(NA,'yes',NA,'yes',NA,NA,NA,NA,'yes','yes',NA,'no', 'no',NA,NA,'yes',
'no','yes','no','yes','no', 'yes',NA, 'no','yes', 'no'))
id x
1 1 <NA>
2 1 yes # 1st yes
3 1 <NA>
4 1 yes # 2nd yes, only NA between, yes is considered as consecutive -> keep group 1
5 1 <NA>
6 1 <NA>
7 2 <NA>
8 2 <NA>
9 2 yes # 1st yes
10 2 yes # 2nd yes, yes is consecutive -> keep group 2
11 2 <NA>
12 3 no
13 3 yes # 1st yes
14 3 <NA>
15 3 <NA>
16 3 yes # 2nd yes -> keep group 3
17 4 no
18 4 yes # 1st yes
19 4 no # "no"
20 4 yes # 2nd yes. a "no" between the two 'yes' -> remove group
21 4 no
22 5 yes # 1st yes
23 5 <NA>
24 5 no # "no"
25 5 yes # 2nd yes. a "no" between the two 'yes' -> remove group
26 5 no
期望的输出
1 1 <NA>
2 1 yes
3 1 <NA>
4 1 yes
5 1 <NA>
6 1 <NA>
7 2 <NA>
8 2 <NA>
9 2 yes
10 2 yes
11 2 <NA>
12 3 no
13 3 yes
14 3 <NA>
15 3 <NA>
16 3 yes
id 4 和 id 5 应该被删除,因为它们不符合每组 'id' 列 'x' 的两个连续"is"值的标准,无论两个 yes 之间的 NA
值如何值(value)观。
我试过用
data1<-data %>% group_by(id) %>%
mutate(x_lag = lag(x),
is_two_yes = x == 'yes' & x_lag == 'yes') %>%
filter(any(is_two_yes)) %>%
select(-is_two_yes,-x_lag)
最佳答案
我们可以添加一个变量 a
来引用 2 --> yes
, 1 --> no
和 0 --> NA
,然后过滤以排除具有 NA
的行,然后使用 zoo::rollsum
和 2's 的窗口,所以如果我们得到值 4 那么这个组有两个连续的yes
library(tidyverse)
data |>
mutate(a = case_when(x == "yes" ~ 2 , x == "no" ~ 1 , TRUE ~ 0)) |>
group_by(id) |> filter(a != 0) |>
mutate(b = c(first(a) , zoo::rollsum(a , 2))) |>
summarise(groups_to_keep = id[which(b == 4)]) -> gk
data |> filter(id %in% gk$groups_to_keep)
id x
1 1 <NA>
2 1 yes
3 1 <NA>
4 1 yes
5 1 <NA>
6 1 <NA>
7 2 <NA>
8 2 <NA>
9 2 yes
10 2 yes
11 2 <NA>
https://stackoverflow.com/questions/73267575/