从前一列中减去一列 [英] Subtract one column from previous column

查看:42
本文介绍了从前一列中减去一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样本数据

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,其中有四列用于测量累积距离.我想创建新列,给出每列的实际距离,即从前一列中减去下一列.例如该表应如下所示:

I have some IDs for which there are four columns which measure cumulative distance. I want to create new column that gives the actual distance for each column i.e. subtract the next column from previous column. For e.g. the table should look like this:

       ID DistA DistB DistC DistD
   1   1    10     5    5     40
   2   2     8    27    5     15
   3   3    15    25    10    5
   4   4    22    11    12    3 
   5   5    15    5     10    20

更长的方法是

dfData$disA <- dfData$DistA
dfData$disB <- dfData$DistB - dfData$DistA
dfData$disC <- dfData$DistC - dfData$DistB
dfData$disD <- dfData$DistD - dfData$DistC

是否有更短的方法来执行此操作,例如:

Is there a shorter way to do this something like:

  apply(dfData,1,function(x) ???)

推荐答案

是的,你想要 diff...

dfData[,-c(1:2)] <- t(apply(dfData[,-1], 1, diff))

dfData
  ID DistA DistB DistC DistD
1  1    10     5     5    40
2  2     8    27     5    15
3  3    15    25    10     5
4  4    22    11    12     3
5  5    15     5    10    20

这篇关于从前一列中减去一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆