Recommand · June 11, 2021 0

Relabelling a vector of repeating bouts of 0 1 so each bout of 1 is unique in R

I’ve got a dataframe that looks something like this:

time <- c(1:250)
trial <- rep(1, 250)
X <- sample(200, 250, replace=TRUE)
Y <- sample(200, 250, replace=TRUE)
follow <- c(rep(0, 20), rep(1, 25), rep(0, 5), rep(1, 50), rep(0, 55), rep(1, 30), rep(0, 35), rep(1, 10), rep(0, 20))
df <- as.data.frame(cbind(trial, time, X, Y, follow))

I’ve got a vector called follow, which just acts as a label for when a certain behavior is being exhibited. However, I’d like each instance of when 1 appears to be unique, like this:

time <- c(1:250)
trial <- rep(1, 250)
X <- sample(200, 250, replace=TRUE)
Y <- sample(200, 250, replace=TRUE)
follow <- c(rep(0, 20), rep(1, 25), rep(0, 5), rep(2, 50), rep(0, 55), rep(3, 30), rep(0, 35), rep(4, 10), rep(0, 20))
df <- as.data.frame(cbind(trial, time, X, Y, follow))

Is there a good way to do this? Thanks all!