Search code examples
rmaxrow

R ROWMAX Based On Criteria


data=data.frame("id"=c(1,2,3,4),
"score1"=c(1,1,2,1),
"score2"=c(1,2,3,3),
"score3"=c(2,3,1,1),
"score4"=c(3,4,4,2),
"score1WANT"=c(1,1,2,1),
"score2WANT"=c(1,2,3,3),
"score3WANT"=c(2,3,3,3),
"score4WANT"=c(3,4,4,3))

Here there are four possible scoring options: 1,2,3,4.

If any 'score' equals to 3 then all subsequent scores equals to 3 UNLESS there is a 4. So as example: 1 3 2 2 should be change to 1 3 3 3 . 3 2 3 4 should be change to 3 3 3 4.

I try to do this with ROWMAX but the problem is that there is a 4 and so then it sets values to 4 if there is a 4.


Solution

  • We need cummax and assuming this needs to be general

    data[2:5] <- t(apply(data[2:5], 1, cummax))
    

    If the condition is only for value 3

    data[2:5] <- t(apply(data[2:5], 1, function(x) {
          i1 <- which(x == 3)
          i2 <- which(x == 4)
         if(length(i2) > 0) replace(x, i1:(i2-1), 3) else replace(x, i1:length(x), 3)}))