简体   繁体   English

R编程:如何计算数据框中两个单元格之间的差异并将其保存在新列中

[英]R programming: How can I compute the difference between two cells in a data frame and save them in a new column

Trying to learn R and am stuck on an autocorrelation example. 试图学习R并坚持自相关的例子。 I want to regress the difference in x against the difference in y. 我想回归x中的差异与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. 我在数据框中有x和y,并希望将x2 - x1的差异保存在一个新列中,例如dx。 I have no idea how to go about this. 我不知道该怎么做。

what I have: 是)我有的:

data1 数据1

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 with transform : 使用带transform diff

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)))

Yielding: 产量:

  x y dx dy
1 5 3 NA NA
2 8 9  3  6
3 3 1 -5 -8
4 1 5 -2  4

And as og dplyr : 和og dplyr一样

library(dplyr)

dat %>%
    mutate(dx=c(NA, diff(x)), dy=c(NA, diff(y)))

Use diff , and stick an NA to the beginning of the resulting vectors. 使用diff ,并将NA粘贴到结果向量的开头。

eg 例如

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R如何计算数据框中行之间的差异 - R how can I calculate difference between rows in a data frame 如何将3列数据帧保存到R中的NetCDF文件中? - How can I save a 3 column data frame into a NetCDF file in R? 如何从三个不同列中选择10个最大值并将它们保存在R中的新数据框中? - How can I select the 10 largest values from three different columns and save them in a new data frame in R? 如何保存两行之间的差异,同时将其保存在 R 的同一 data.frame 中? - How to save the difference between the two rows while saving it in the same data.frame in R? 如何在数据框中的一列和所有其他列之间执行线性回归并将 r 平方值保存在新数据框中? - How to perform linear regression between one column and all other columns in a data frame and save r squared values in new data frame? R 生成数据框中两列的差异 - R generating the difference of two column in a data frame 引用data.frame的前几行以计算R中的新列 - Referencing previous rows of a data.frame to compute a new column in R 计算来自不同数据帧的两列之间的R的相关性 - compute correlation in R between two columns from different data frame 如何按不同的列比较 R 数据帧中的两行并对它们执行操作? - How can I compare two rows in R data frame by different columns and perform an operation on them? 如何计算列的两个值之间的相关性? - How can I compute correlation between two values of a column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM