I have the following dataframe:
Group<-c(A,A,A,B,B,B)
Dates<-(c("01-01-2000","02-01-2000","03-01-2000","01-05-2020","02-05-2020","03-05-2020"))
Departure<-c("01-01-2000","01-01-2000","01-01-2000",NA,NA,NA)
Arrival<-c(NA,NA,NA,"03-02-2020","03-02-2020","03-02-2020")
Dates<-data.frame(Dates,Departure,Arrival)
Dates
Group Dates Departure Arrival
1 01-01-2000 02-01-2000 <NA>
1 02-01-2000 02-01-2000 <NA>
1 03-01-2000 02-01-2000 <NA>
2 01-05-2000 <NA> 31-12-2020
2 02-05-2000 <NA> 31-12-2020
2 03-05-2000 <NA> 31-12-2020
Here is what I want to do:
- For the "Departure" column: if the value is NOT NA, leave as is. If the value is NA, then replace with the FIRST value of the "Dates" column within each group.
- For the "Arrival" column: if the value is NOT NA, leave as is. If the value is NA, then replace with the LAST value of the "Dates" column within each group.
I would then obtain the following dataframe:
Group Dates Departure Arrival
1 01-01-2000 02-01-2000 03-01-2000
1 02-01-2000 02-01-2000 03-01-2000
1 03-01-2000 02-01-2000 03-01-2000
2 01-05-2000 01-05-2000 31-12-2020
2 02-05-2000 01-05-2000 31-12-2020
2 03-05-2000 01-05-2000 31-12-2020
I'm thinking of using a combination of if else and group_by from dplyr, but beyond that I'm stuck. Any suggestions would be appreciated!!