I wish to have the factor that happened earlier as a new row.
This is my data
df <- data.frame (id =c(1,1,2,2,1), date= c(20161002,20151019, 20160913, 20161117, 20160822), factor = c("A" , "B" ,"C" ,"D" ,"H"))
and I want to have an additional row that shows the immediate last factor. So, my ideal output is:
id date factor col2
1 1 20161002 A H
2 1 20151019 B NA
3 2 20160913 C NA
4 2 20161117 D C
5 1 20160822 H B
For instance, for id 1 in the first row the previous factor happend in 20160822 and its value was H
.
What I tied does not consider the last date
library (dplyr)
library(zoo)
mutate( col2 = na.locf(factor))