I'd like to use dplyr::lag()
with ifelse
using 3 conditions and rules. If factor S
then NA
, if the factor is D
then monitor
, but if D
repeat continuously and just only continuously three-time or more, them "Combat"
I try to do:
test<-NULL
test$groups <-c("S","D","D","D","D","S","D","D","S")
test <- as.data.frame(test)
test%>%mutate(decision = ifelse(groups == "D", "Monitor",ifelse(groups == "D" & lag(groups, 2) == "D","Monitor", ifelse(groups == "D" & lag(groups, 3) == "D", "Combat",NA))))
groups decision
1 S <NA>
2 D Monitor
3 D Monitor
4 D Monitor
5 D Monitor
6 S <NA>
7 D Monitor
8 D Monitor
9 S <NA>
But is wrong, my correct output is:
groups decision
1 S <NA>
2 D Monitor
3 D Monitor
4 D Combat
5 D Combat
6 S <NA>
7 D Monitor
8 D Monitor
9 S <NA>
Please, any help with it?
CodePudding user response:
library(data.table)
setDT(test)[,id:=rleid(groups)][groups=="D",decision:=fifelse(1:.N>=3, "Combat","Monitor"), by=id][,.(groups,decision)]
Output:
groups decision
<char> <char>
1: S <NA>
2: D Monitor
3: D Monitor
4: D Combat
5: D Combat
6: S <NA>
7: D Monitor
8: D Monitor
9: S <NA>
Or, you can also do like this (but I still incorporate the use of data.table::rleid
test %>%
group_by(id:=data.table::rleid(groups)) %>%
mutate(decision = case_when(
groups=="D" & row_number()>=3 ~ "Combat",
groups=="D" & row_number()<3 ~"Monitor",
TRUE~as.character(NA))) %>%
ungroup() %>%
select(!id)
# A tibble: 9 x 2
groups decision
<chr> <chr>
1 S NA
2 D Monitor
3 D Monitor
4 D Combat
5 D Combat
6 S NA
7 D Monitor
8 D Monitor
9 S NA