You can't reference a variable in it initial definition. What we can do is do it in multiple passes.
When I look at your conditions:
nothing.after.click = (lag(click) == TRUE & interaction == FALSE) |
(lag(nothing.after.click) == TRUE & interaction == FALSE)
I see that interaction == FALSE
in both possibilities. So, if interaction
is TRUE
, then nothing.after.click
(from here on out nac
) is definitely FALSE. Otherwise, I'm not sure yet so I'll set it to NA
. That's my first pass:
dat %>% mutate(nac = ifelse(interaction, FALSE, NA))
We've taken care of the interaction == FALSE
part, the next pass will be the lag(click) == TRUE
part of your or clause. For anything that is NA
, therefore undecided as yet, it will be TRUE if lag(click)
is TRUE, otherwise we'll leave it untouched. (== TRUE
is redundant, so I left it out.)
dat %>% mutate(nac = ifelse(interaction, FALSE, NA),
nac = ifelse(lag(click) & is.na(nac), TRUE, nac))
For the last pass is the lag(nac)
part, anything that is still undefined is set to the previous defined value. This is a job for zoo:na.locf
(locf stands for "last observation carried forward"):
library(zoo)
dat %>% mutate(nac = ifelse(interaction, FALSE, NA),
nac = ifelse(lag(click) & is.na(nac), TRUE, nac),
nac = na.locf(nac))
# time click interaction nac
# 1 407 FALSE TRUE FALSE
# 2 408 TRUE TRUE FALSE
# 3 409 FALSE FALSE TRUE
# 4 410 FALSE FALSE TRUE
# 5 411 FALSE FALSE TRUE
# 6 412 FALSE FALSE TRUE
# 7 413 FALSE FALSE TRUE
# 8 414 FALSE FALSE TRUE
# 9 415 FALSE FALSE TRUE
# 10 416 FALSE FALSE TRUE
# 11 417 FALSE FALSE TRUE
# 12 418 FALSE FALSE TRUE
# 13 419 FALSE FALSE TRUE
# 14 420 FALSE FALSE TRUE
# 15 421 FALSE FALSE TRUE
# 16 422 FALSE FALSE TRUE
# 17 423 FALSE FALSE TRUE
# 18 424 FALSE FALSE TRUE
# 19 425 FALSE FALSE TRUE
# 20 426 FALSE FALSE TRUE
# 21 427 FALSE FALSE TRUE
# 22 428 FALSE FALSE TRUE
# 23 429 FALSE FALSE TRUE
# 24 430 FALSE FALSE TRUE
# 25 431 FALSE FALSE TRUE
# 26 432 FALSE FALSE TRUE
# 27 433 FALSE FALSE TRUE
# 28 434 FALSE FALSE TRUE
# 29 435 FALSE TRUE FALSE
# 30 436 FALSE FALSE FALSE
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…