I have a dataframe with just dates of medical checkups and presence of infection (yes/no), and I want to add a third column representing the date of the last infection. The new last_infection
column should have NA
if the patient has had no previous infection. If they have had previous infection, it should show the date of the most recent visit where they tested "yes" for infection.
I want the output to look like this:
date infection last_infection
01-01-18 no NA
06-01-18 no NA
07-01-18 yes NA
09-01-18 no 07-01-18
01-01-19 no 07-01-18
02-01-19 yes 07-01-18
03-01-19 yes 02-01-19
04-01-19 no 03-01-19
05-01-19 no 03-01-19
How can I do this in R? Can a function like lag()
check for a condition, or should I do something else entirely?