从上一行减去R [英] Subtract from the previous row R
本文介绍了从上一行减去R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df< - data.frame(start = c(5,4, 2),end = c(2,6,3))
开始结束
5 2
4 6
2 3
我想要以下结果:
start end diff
5 2
4 6 1
2 3 -1
本质上是:
end [2](第二行) - 开始[1] = 6-5 = 1
和 end [3] - 开始[2] = 3-4 = -1
在R中有什么好的方法?
解决方案
p>只需简单的向量减法就可以工作
df $ diff< - c(NA,df [2:nrow ),2] - df [1:(nrow(df)-1),1])$ b
$ b开始结束diff
1 5 2 NA
2 4 6 1
3 2 3 -1
I have a dataframe like so:
df <- data.frame(start=c(5,4,2),end=c(2,6,3))
start end
5 2
4 6
2 3
And I want the following result:
start end diff
5 2
4 6 1
2 3 -1
Essentially it is:
end[2] (second row) - start[1] = 6-5=1
and end[3] - start[2] = 3-4 = -1
What is a good way of doing this in R?
解决方案
Just a simple vector subtraction should work
df$diff <- c(NA,df[2:nrow(df), 2] - df[1:(nrow(df)-1), 1])
start end diff
1 5 2 NA
2 4 6 1
3 2 3 -1
这篇关于从上一行减去R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文