I have the following dataframe
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 3
2 2002 3
2 2003 3
2 2004 3
I want to update each value in "level" column by ID based on the previous one if the previous one is smaller.
the dataframe should look like this
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 1
2 2002 1
2 2003 1
2 2004 1
I tried using shift from data table but it only changes one cell.
I got this result
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 1
2 2002 3
2 2003 3
2 2004 3
>Solution :
You can use
df$level <- Reduce(function(...) min(..., na.rm = T), df$level, accumulate = T)
to obtain your desired result:
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 1
2 2002 1
2 2003 1
2 2004 1