lundi 20 avril 2020

Matching the previous row in a specific column and performing a calculation in R

I currently have a data file that resembles this:

R ID A B    
1 A1 0 0  
2 A1 2 4  
3 A1 4 8    
4 A2 0 0  
5 A2 3 3  
6 A2 6 6

I would like to write a script that will only calculate "(8-4)/(4-2)" from the previous row only if the "ID" matches. For example, in the output for a column "C" in row 3, if A1 == A1 in the "ID" column, then (8-4)/(4-2) = 2. If A1 != A1, then output is 0.

I would like the output to be like this:

R ID A B C   
1 A1 0 0 0  
2 A1 2 4 2  
3 A1 4 8 2     
4 A2 0 0 0  
5 A2 3 3 1   
6 A2 6 6 1  

Hopefully I explained this correctly in a non-confusing manner.

Aucun commentaire:

Enregistrer un commentaire