Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting the first row from all following rows

Tags:

r

dplyr

From the following data set I want to subtract the values in the row labeled "BLK" from all subsequent rows (regardles of their lables).

 label   Int_A Int_B Int_C
 BLK     10    20    30    
 SMP     12.5  22.5  35    
 STD     15    25    40    

Desired output:

 label   Int_A Int_B Int_C 
 BLK     10    20    30    
 SMP     2.5   2.5   5    
 STD     5     5     10   

It does not matter if the BLK-row remains unchanged or will be set to zero.

Unfortunately, all answers I found consider only one variable, not all. I tried using the dplyr package, especially rowwise() and transmute() (there is no need to keep the old values) but failed also in calling an entire row and not only a certain variable. In basic R I also tried (and failed) but working with dplyr would be preferable, as the entire data set could exist of more than one of these sections and subsetting is easy with group_by() using a separate column.

I would be very glad if you could give me some advise or the required code.

like image 500
T. Rose Avatar asked Sep 28 '17 11:09

T. Rose


1 Answers

If we need to subtract the first row from others, use mutate_at to specify the index of numeric columns or mutate_if and then subtract the first element from the all the elements of the column

library(dplyr)
df1 %>% 
    mutate_at(2:4, funs(c(first(.), (. - first(.))[-1])) )

Or with mutate_if

df1 %>%
    mutate_if(is.numeric, funs(c(first(.), (. - first(.))[-1])) )
like image 99
akrun Avatar answered Oct 30 '22 10:10

akrun