使用一列数据框,我想从上一行中减去days值,并创建一个新的列,称为interval,并使用差值。运行创建的代码时,我会得到另外两列。 .index和.value。
我尝试了多个运算符
deploy$interval <- getInterval(deploy$days[i], i, y)
deploy$interval = getInterval(deploy$days[i], i, y)
deploy <- data.frame(
days = c(5,10,40,20,15,5,3,7,34,20,16,7,5,8,9,6,10,5,15,9,7,6,9,7,8,9,6,7,8,6,9,7,8,8,6,7,5,6,7,5,6,5,7,5,6,4,5,4,5,6,4,5,6,4,5,3,5)
)
getInterval <- function(x, i, c){
if (i == 1) {
y = 0
z = x
} else {
y = x-z
z = x
}
return (y)
}
y <- nrow(deploy)
for (i in 1:y) {
deploy$interval <- getInterval(deploy$days[i], i, y)
}
print (deploy)
获得一个.index和.value列。仅预期间隔列。顺便说一句,interval.index列确实包含了我一直在寻找的值...
obs days interval.index interval.value
1 5 0 -120
2 10 -5 -995
3 40 -35 -63995
4 20 -15 -7995
5 15 -10 -3370
6 5 0 -120