Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: change cell value by comparing to cell above

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading