I have a dataframe with a variable var
that was measured at time points 0 to 2. Like this:
df <- data.frame(id= letters[1:5],
var0= c(1:3, NA, 5),
var1= c(11, NA, NA, 14:15),
var2= c(NA, NA, NA, NA, 25))
df
id var0 var1 var2
1 a 1 11 NA
2 b 2 NA NA
3 c 3 NA NA
4 d NA 14 NA
5 e 5 15 25
For each row, i.e. for each person, I want to keep the newest non-missing value. So the desired output is:
id var0 var1 var2 last_val
1 a 1 11 NA 11
2 b 2 NA NA 2
3 c 3 NA NA 3
4 d NA 14 NA 14
5 e 5 15 25 25
How to do this within the tidyverse packages?
A trick with
left_join
+pivot_longer
gives