Tra*_*vis 5 r subtraction dataframe
试图学习R并坚持自相关的例子.我想回归x中的差异与y的差异.我在数据框中有x和y,并希望将x2 - x1的差异保存在一个新列中,例如dx.我不知道该怎么做.
是)我有的:
数据1
x y
5 3
8 9
3 1
1 5
. .
. .
. .
Run Code Online (Sandbox Code Playgroud)
我想得到什么:
data1.dif
x y dx dy
5 3 NA NA
8 9 3 6
3 1 -5 -8
1 5 -2 4
. . . .
. . . .
Run Code Online (Sandbox Code Playgroud)
使用diff有transform:
dat <- read.table(text="x y
5 3
8 9
3 1
1 5", header=T)
transform(dat, dx=c(NA, diff(x)), dy=c(NA, diff(y)))
Run Code Online (Sandbox Code Playgroud)
产量:
x y dx dy
1 5 3 NA NA
2 8 9 3 6
3 3 1 -5 -8
4 1 5 -2 4
Run Code Online (Sandbox Code Playgroud)
和og dplyr一样:
library(dplyr)
dat %>%
mutate(dx=c(NA, diff(x)), dy=c(NA, diff(y)))
Run Code Online (Sandbox Code Playgroud)
使用diff,并将NA粘贴到结果向量的开头.
例如
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
Run Code Online (Sandbox Code Playgroud)