Also, here's an alternative solution that also uses cumsum()
, but in a less direct way:
visits |>
# flag Sasquatch days
mutate(sasquatch = visitor == 'Sasquatch') |>
# if we assign a value of 0 to Sasquatch days, and 1 to the rest,
# the cumulative sum will be constant during Sasquatch visits, but
# also different for each visit
mutate(visit = if_else(sasquatch, cumsum(!sasquatch), NA)) |>
# remove 'sasquatch' column since no longer needed
select(!sasquatch) |>
# convert 'visit' to a factor so corresponding ordinal can be extracted
mutate(visit = visit |> factor() |> as.numeric())
This:
visit |> factor() |> as.numeric()
is a bit of a hack, but I'm not sure of a way to convert to ordinal values more cleanly.