样本数据
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,其中有四列用于测量累积距离。我想创建新列,给出每列的实际距离,即从上一列中减去下一列。
例如该表应如下所示:
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
有没有更短的方法可以做到这一点,例如:
apply(dfData,1,function(x) ???)