I have 3 columns with visit dates (year1, year2, year3) and I'm trying to make a column that is called last_visit that has whatever the most recent visit was. The code I wrote was like this:
#Fake data set similar to what my data set looks like sometimes
playdata <- as.data.frame(
year1_visit = c("2020-09-07", "2018-10-05", ""),
year2_visit = c("2021-09-08", "2019-10-15", ""),
year3_visit = c("2022-09-05", "", ""))
#Looks something like this:
id | year1_visit | year2_visit | year3_visit
---|-------------|-------------|-------------
01 | 2020-09-07 | 2021-09-07 | 2022-09-05 #person who has come for all 3 visits
---|-------------|-------------|-------------
02 | 2018-10-05 | 2019-10-15 | #person came for 1st two needs 3rd
---|-------------|-------------|-------------
03 | | | #person who hasn't been scheduled yet
---|-------------|-------------|-------------
#Code to make most recent visit col that is not working
last_visit <- playdata %>%
mutate(last_visit =
max(year1_visit,
year2_visit,
year3_visit))
The issue is it is calculating the max for only one random observation in the middle of the data set (243 out of 500 something) and populating the entire column of last_visit with that output for all observations. So all of last_visit is the same date, and it's the last visit for observation 243. Does anyone know why this would happen and/or how to fix it?
I could fix this with a for loop but I feel like I shouldn't have to. I feel like this should just work. Thank you for the help!