I have a dataframe (or datatable, if that's easier) with incomplete rows:
Input
ID Var1 Var2 Var3
1 2 5 1
2 12 3
3 8
4 4
Code
d <- data.frame(
ID = 1:4,
Var1 = c(2, 12, 8, 4),
Var2 = c(5, 3, NA, NA),
Var3 = c(1, NA, NA, NA)
)
library(data.table)
d <- fread("
ID Var1 Var2 Var3
1 2 5 1
2 12 3 NA
3 8 NA NA
4 4 NA NA
")
The empty cells are always at the end of a row.
I would like to fill the empty cells in each row with the value in the last non-empty cell in that row, e.g.:
ID Var1 Var2 Var3
1 2 5 1
2 12 3 -> 3
3 8 -> 8 -> 8
4 4 -> 4 -> 4
How do I do that?
I don't want to use dplyr and I don't want to fill columns.