I want to assign consecutive trial numbers (1-16) to a long dataframe depending on certain values of other variables.
It should look like this (simplified):
value trial_no
videoA 1
other 1
videoB 2
other 2
other 2
videoC 3
...
This basically does what I want, but it just assigns the row numbers.
df2 <- df1 %>%
mutate(trial_no = case_when(grepl('video', value) ~ row_number())) %>%
fill(trial_no)
This might do what I want, but yet it assigns 16 to all.
for (vid in c(1:16)) {
df2 <- df1 %>%
mutate(trial_no = case_when(grepl("video", value) ~ vid)) %>%
fill(trial_no)
}
I'm pretty sure there is an easy solution to this. Any help is very much appreciated.
CodePudding user response:
Using grepl
and count the TRUE
s
transform(dat, trial_no=cumsum(grepl('video', value)))
# value trial_no
# 1 videoA 1
# 2 other 1
# 3 videoB 2
# 4 other 2
# 5 other 2
# 6 videoC 3
Data:
dat <- structure(list(value = c("videoA", "other", "videoB", "other",
"other", "videoC")), class = "data.frame", row.names = c(NA,
-6L))