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

How to calculate values for the first row that meets a certain condition?

I have the following dummy dataframe:

t <- data.frame(
           a= c(0,0,2,4,5),
           b= c(0,0,4,6,5))
a   b
0   0
0   0
2   4
4   6
5   5

I want to replace just the first value that it is not zero for the column b. Imagine that the row that meets this criteria is i. I want to replace t$b[i] with t[i+2]+t[i+1] and the rest of t$b should remain the same. So the output would be

a   b
0   0
0   0
2  11
4   6
5   5

In fact the dataset is dynamic so I cannot directly point to a specific row, it has to meet the criteria of being the first row not equal to zero in column b.
How can I create this new t$b?

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

>Solution :

Here is a straight forward solution in base R:

t <- data.frame(
  a= c(0,0,2,4,5),
  b= c(0,0,4,6,5))


ind <- which(t$b > 0)[1L]
t$b[ind] <- t$b[ind+2L] + t$b[ind+1L]
t
  a  b
1 0  0
2 0  0
3 2 11
4 4  6
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