如何用上一列减去下一列并在其后创建新列?

时间:2020-11-04 01:34:39

标签: r

这里有关于stackoverflow的问题,该问题是关于如何像this这样的上一列来对列进行区分的。我的问题有点不同,我想在该差异之后创建一个新列,而不修改现有列

样本数据:

dfData <- data.frame(ID = c(1, 2, 3, 4, 5), 
                  DistA = c(10, 8, 15, 22, 15), 
                 DistB = c(15, 35, 40, 33, 20),
                 DistC = c(20,40,50,45,30),
                 DistD = c(60,55,55,48,50))

   ID DistA DistB DistC DistD
 1  1    10    15    20    60
 2  2     8    35    40    55
 3  3    15    40    50    55
 4  4    22    33    45    48
 5  5    15    20    30    50



预期输出:

   ID DistA DistB DiffB-A  DistC DistD  Diff D-C
 1  1    10    15   05      20    60    40
 2  2     8    35   27      40    55    15
 3  3    15    40   25      50    55    05
 4  4    22    33   11      45    48    03
 5  5    15    20    5      30    50    20
     

用上一列减去下一列,然后在其后创建新列

1 个答案:

答案 0 :(得分:0)

如果要每两列相减,我们可以使用split.default将数据分成两列,并用第一列减去第二列。

cols <- ceiling(seq_along(dfData[-1])/2)
new_cols <- tapply(names(dfData[-1]), cols, function(x) 
                   sprintf('diff_%s', paste0(x, collapse = '')))
dfData[new_cols] <- sapply(split.default(dfData[-1], cols), function(x) 
                     x[[2]] - x[[1]])
dfData

#  ID DistA DistB DistC DistD diff_DistADistB diff_DistCDistD
#1  1    10    15    20    60               5              40
#2  2     8    35    40    55              27              15
#3  3    15    40    50    55              25               5
#4  4    22    33    45    48              11               3
#5  5    15    20    30    50               5              20