R编程:如何计算数据帧中两个单元格之间的差异并将其保存在新列中 [英] R programming: How can I compute the difference between two cells in a data frame and save them in a new column
本文介绍了R编程:如何计算数据帧中两个单元格之间的差异并将其保存在新列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有什么:
data1
xy
5 3
8 9
3 1
1 5
。 。
。 。
。 。
我想得到什么:
data1.dif
xy dx dy
5 3 NA NA
8 9 3 6
3 1 -5 -8
1 5 -2 4
。 。 。 。
。 。 。 。
解决方案
使用 diff
,并将NA粘贴到结果矢量的开头。
例如
data1< - read.table(text ='xy
1 5 3
2 8 9
3 3 1
4 1 5')
#diff计算连续对
#矢量元素之间的差异
diff(data1 $ x)
[1] 3 -5 -2
#将diff应用于每一列data1,将NA行绑定到开头,
#并将结果列绑定到原始df
data1.dif< - cbind(data1,rbind(NA,apply(data1,2,diff)))
名称(data1.dif)< - c('x','y ','dx','dy')
data1.dif
xy dx dy
1 5 3 NA NA
2 8 9 3 6
3 3 1 -5 -8
4 1 5 -2 4
Trying to learn R and am stuck on an autocorrelation example. I want to regress the difference in x against the difference in y. I have x and y in a data frame, and would like the difference of x2 - x1 to be saved in a new column say dx. I have no idea how to go about this.
what I have:
data1
x y
5 3
8 9
3 1
1 5
. .
. .
. .
what I would like to get:
data1.dif
x y dx dy
5 3 NA NA
8 9 3 6
3 1 -5 -8
1 5 -2 4
. . . .
. . . .
解决方案
Use diff
, and stick an NA to the beginning of the resulting vectors.
e.g.
data1 <- read.table(text=' x y
1 5 3
2 8 9
3 3 1
4 1 5')
# diff calculates the difference between consecutive pairs of
# vector elements
diff(data1$x)
[1] 3 -5 -2
# apply diff to each column of data1, bind an NA row to the beginning,
# and bind the resulting columns to the original df
data1.dif <- cbind(data1, rbind(NA, apply(data1, 2, diff)))
names(data1.dif) <- c('x', 'y', 'dx', 'dy')
data1.dif
x y dx dy
1 5 3 NA NA
2 8 9 3 6
3 3 1 -5 -8
4 1 5 -2 4
这篇关于R编程:如何计算数据帧中两个单元格之间的差异并将其保存在新列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文