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

For each row in a data frame, replace Non-NA values with the previous maximum number up to that point in R

I have a dataset in R where the first column represent a geographic location. All subsequent columns represent counts from each consecutive year from 1800-2020.

For each row, I only want Non-NA numbers to increase. So if a subsequent Non-NA value is lower than a previous one, change it to the maximum value up to that point.

For example it looks like this now:

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

Location 1800 1801 1802 1803 1804
A 1 3 2 1 3
B 1 2 3 1 5
C 0 1 5 1 3

I want it to look like this:

Location 1800 1801 1802 1803 1804
A 1 3 3 3 3
B 1 2 3 3 5
C 0 1 5 5 5

>Solution :

df1 <- df   
df1[-1] <- matrixStats::rowCummaxs(as.matrix(df[-1]))
df1
  Location X1800 X1801 X1802 X1803 X1804
1        A     1     3     3     3     3
2        B     1     2     3     3     5
3        C     0     1     5     5     5
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