简体   繁体   English

从所有后续行中减去第一行

[英]Subtracting the first row from all following rows

From the following data set I want to subtract the values in the row labeled "BLK" from all subsequent rows (regardles of their lables). 从以下数据集中,我想从所有后续行(它们的标签的片段)中减去标记为“BLK”的行中的值。

 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. BLK行保持不变或将设置为零无关紧要。

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. 我尝试使用dplyr包,尤其是rowwise()rowwise() transmute()不需要保留旧值)但是在调用整行而不仅是某个变量时也失败了。 In basic RI 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. 在基本的RI中也尝试过(并且失败了)但是使用dplyr会更好,因为整个数据集可能存在多个这些部分,并且group_by()使用单独的列很容易进行子集化。

I would be very glad if you could give me some advise or the required code. 如果你能给我一些建议或所需的代码,我将非常高兴。

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 如果我们需要从其他行中减去first行,请使用mutate_at指定数字列的索引或mutate_if ,然后从列的所有元素中减去第first元素

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

Or with mutate_if 或者使用mutate_if

df1 %>%
    mutate_if(is.numeric, funs(c(first(.), (. - first(.))[-1])) )
df[-1, -1] <- df[-1 , -1] - df[rep(1, nrow(df) - 1), -1]
df
#   label Int_A Int_B Int_C
# 1   BLK  10.0  20.0    30
# 2   SMP   2.5   2.5     5
# 3   STD   5.0   5.0    10

From relevant rows and columns df[-1 , -1] , subtract the first row rep eated to the necessary number of rows ( nrow(df) - 1 ). 从相关的行和列df[-1 , -1] ,减去rep所需行数的第一行( nrow(df) - 1 )。

As an alternative using no packages: 作为替代使用没有包:

diff is a matrix of the same size like df, with first row 0 and the rest equal to the 1st row in df. diff是与df相同大小的矩阵,第一行为0,其余为df中的第一行。 Then simply subtract. 然后简单地减去。

df <- mtcars

diff <- matrix(c(rep(0,ncol(df)),rep(as.numeric(df[1,]),nrow(df)-1)),nrow=nrow(df),ncol=ncol(df),byrow=T)

df - diff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM