mercredi 31 janvier 2018

R How to select (and do calculations with) a row and the exact row beneath it in R

thanks in advance for helping! I'm a beginner in R so apologies in advance for any inconvenience. I tried my hardest to make it a understandable question.

My dataframe looks like this:

      var1      var2    var3
1     0         5       "other"
2     25        3       "sample"
3     4         5       "other"
4     60        5       "other"
5     4         5       "other"
6     60        5       "other"
7     25        3       "sample"
8     4         8       "other"
9     60        7       "other"
10    4         3       "other"  
11    25        27      "sample"  
12    4         9       "other"   
13    30        4       "other"   

I would like to add a column that for all rows that equal var3=="sample" gives the calculation of the value in var2 column minus the value in var 2 column of the row beneath the "sample" row. That would look like this:

      var1      var2    var3      var4
1     0         5       "other"   NA
2     25        25      "sample"  20
3     4         5       "other"   NA
4     60        5       "other"   NA
5     4         5       "other"   NA
6     60        5       "other"   NA
7     25        13      "sample"  8
8     4         5       "other"   NA
9     60        5       "other"   NA
10    4         3       "other"   NA
11    25        27      "sample"  18
12    4         9       "other"   NA
13    30        4       "other"   NA

I have tried

if(df$var3=="sample") {df$var4<-(df$var2-df$var2[+1,])}

But that obviously doesn't work. How to do a calculation with a column from a specific row and the exact row beneath it?
I'm very sorry if this is a stupid question, I really searched stack overflow for a long time but couldn't find a solution.

Aucun commentaire:

Enregistrer un commentaire