Getting the maximum value to a point in rows in a matrix in R

I am trying to create a link to the maximum value observed at a particular point in time. Here is an example of what I'm trying to do. Each line is processed individually. I have considered some combination of row and column application, but I want to be able to calculate this for the whole matrix right away without using loops.

Say I have a matrix

1, 2, 3, 2, 2, 5, 4, 5, 7

2, 3, 3, 4, 2, 3, 5, 4, 6

I want to create a new matrix that looks like

1, 2, 3, 3, 3, 5, 5, 5, 7

2, 3, 3, 4, 4, 4, 5, 5, 6

Thank.

+3
source share
1 answer

cummax or cumulative maximum is what you need:

dat <- as.matrix(read.csv(text="
1, 2, 3, 2, 2, 5, 4, 5, 7
2, 3, 3, 4, 2, 3, 5, 4, 6",
header=FALSE))

dat
#     V1 V2 V3 V4 V5 V6 V7 V8 V9
#[1,]  1  2  3  2  2  5  4  5  7
#[2,]  2  3  3  4  2  3  5  4  6

t(apply(dat,1,cummax))

#     V1 V2 V3 V4 V5 V6 V7 V8 V9
#[1,]  1  2  3  3  3  5  5  5  7
#[2,]  2  3  3  4  4  4  5  5  6
+4
source

All Articles