Reputation: 403
I have the following variables in a dataset:
UserID | Date | Workplace | First_Workplace
Users are assigned to a workplace (Remote or Office). I'm trying to figure out when each user returned to the office and Workplace no longer equaled First_Workplace. I need to add this data to a new column named Date_Changed.
Sudo code would be something like the below. I just can't figure it out in R:
data %>%
mutate(data, Date_Changed = Date WHEN Workplace != First_Workplace FOR EACH UserID)
Upvotes: 0
Views: 27
Reputation: 887691
We may use which
on the logical values to get the index and select the first index with [1]
library(dplyr)
data %>%
group_by(UserID) %>%
mutate(Date_changed = Date[which(Workplace !=
first(Workplace))[1]]) %>%
ungroup
NOTE: If there is no change, it returns NA
data <- data.frame(UserID = rep(1:3, each = 3),
Workplace = c("A", "A", "B", "A", "A", "A", "C", "C", "C"),
Date = Sys.Date() + 0:8)
Upvotes: 1