减去数据框(或矩阵)中的列

Subtracting columns in a dataframe (or matrix)

我试图在 Excel 中少做一些事情,而在 R 中做更多的事情,但是却陷入了一个简单的计算。我有一个包含数周仪表读数的数据框。我需要计算每周的消耗量,即从上一列中减去一列。例如,在下面的示例中,我需要从 Reading2 中减去 Reading1 并从 Reading3 中减去 Reading2。我的实际数据集包含数百个读数,因此我需要找到一种简单的方法来执行此操作。

SerialNo = c(1,2,3,4,5)
Reading1 = c(100, 102, 119, 99, 200)
Reading2 = c(102, 105, 120, 115, 207)
Reading3 = c(107, 109, 129, 118, 209)
df <- data.frame(SerialNo, Reading1, Reading2, Reading3)
df
  SerialNo Reading1 Reading2 Reading3
1      1        100      102      107
2      2        102      105      109
3      3        119      120      129
4      4         99      115      118
5      5        200      207      209

df[,paste0(names(df)[3:4], names(df)[2:3])] <- df[,names(df)[3:4]] - df[,names(df)[2:3]] 
df
  SerialNo Reading1 Reading2 Reading3 Reading2Reading1 Reading3Reading2
1        1      100      102      107                2                5
2        2      102      105      109                3                4
3        3      119      120      129                1                9
4        4       99      115      118               16                3
5        5      200      207      209                7                2

PS:我假设列的顺序为 1,2,3,...等

这是一个 tidyverse 解决方案,returns 具有类似格式的数据框。它将数据转换为长格式 (pivot_longer),应用 lag 函数,进行减法,然后加宽回原始格式 (pivot_wider)。

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(Reading1:Reading3,
               names_to = "reading",
               names_prefix = "Reading",
               values_to = "value") %>%
  group_by(SerialNo) %>%
  mutate(offset = lag(value, 1),
         measure = value - offset) %>%
  select(SerialNo, reading, measure) %>%
  pivot_wider(names_from = reading,
              values_from = measure,
              names_prefix = "Reading")

>
# A tibble: 5 x 4
# Groups:   SerialNo [5]
  SerialNo Reading1 Reading2 Reading3
     <dbl>    <dbl>    <dbl>    <dbl>
1        1       NA        2        5
2        2       NA        3        4
3        3       NA        1        9
4        4       NA       16        3
5        5       NA        7        2

另一种选择是使用简单的 for 遍历数据框的列。我认为这个解决方案更容易理解,特别是如果您开始使用 R。

#Create a data frame with same rows as your df and number of cols-1
resul<-as.data.frame(matrix(nrow=nrow(df),ncol=(ncol(df)-1)))
#Add the SerialNo column to the first column of results df
resul[,1]<-df[,1]
#Set the name of the first column to SerialNo (as the first colname of df)
colnames(resul)[1]<-colnames(df)[1]

#Loop over the Reading columns of df (from the second column to the last minus 1)
for(i in 2:(ncol(df)-1)){
    #Do the subtraction
    resul[,i] <- df[,i+1]-df[,i]
    #Set the colname for each iteration
    colnames(resul)[i]<-paste0(colnames(df)[i+1],"-",colnames(df)[i])
}

我们可以使用 apply 按行计算连续列之间的差异。

temp <- t(apply(df[-1], 1, diff))
df[paste0('ans', seq_len(ncol(temp)))] <- temp
df

#  SerialNo Reading1 Reading2 Reading3 ans1 ans2
#1        1      100      102      107    2    5
#2        2      102      105      109    3    4
#3        3      119      120      129    1    9
#4        4       99      115      118   16    3
#5        5      200      207      209    7    2