m_c
m_c

Reputation: 516

extracting maximum value of cumulative sum into a new column

A sample of data set:

testdf <- data.frame(risk_11111 = c(0,0,1,2,3,0,1,2,3,4,0), risk_11112 = c(0,0,1,2,3,0,1,2,0,1,0))

And I need output data set which would contain new column where only maximum values of cumulative sum will be maintained:

testdf <- data.frame(risk_11111 = c(0,0,1,2,3,0,1,2,3,4,0), 
                           risk_11111_max = c(0,0,0,0,3,0,0,0,0,4,0),
                           risk_11112 = c(0,0,1,2,3,0,1,2,0,1,0),
                           risk_11112_max = c(0,0,0,0,3,0,0,2,0,1,0))

I am guessing some logical subseting of vectors colwise with apply and extracting max value with position index, and mutate into new variables.
I dont know how to extract values for new variable.
Thanks

Upvotes: 1

Views: 620

Answers (1)

LyzandeR
LyzandeR

Reputation: 37889

Something like this with base R:

lapply(testdf, function(x) {
  x[diff(x) > 0] <- 0
  x
})

And to have all in one data.frame:

dfout <- cbind(testdf, lapply(testdf, function(x) {
  x[diff(x) > 0] <- 0
  x
}))
names(dfout) <- c(names(testdf), 'risk_1111_max', 'risk_1112_max')

Output:

   risk_11111 risk_11112 risk_1111_max risk_1112_max
1           0          0             0             0
2           0          0             0             0
3           1          1             0             0
4           2          2             0             0
5           3          3             3             3
6           0          0             0             0
7           1          1             0             0
8           2          2             0             2
9           3          0             0             0
10          4          1             4             1
11          0          0             0             0

Upvotes: 3

Related Questions