【问题标题】:R programming: How can I compute the difference between two cells in a data frame and save them in a new columnR编程:如何计算数据框中两个单元格之间的差异并将它们保存在新列中
【发布时间】:2012-02-23 00:49:18
【问题描述】:

尝试学习 R 并陷入自相关示例。我想将 x 的差异与 y 的差异进行回归。我在数据框中有 x 和 y,并且希望将 x2 - x1 的差异保存在一个新列中,例如 dx。我不知道该怎么做。

我有什么:

数据1

x   y
5   3
8   9
3   1
1   5
.   .
.   .
.   .

我想得到什么:

data1.dif

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

【问题讨论】:

  • 正如两个答案所说,diff 这样做很舒服,但如果你想回到基础(即忘记)然后看看data1[-1,] - data1[-nrow(data1),],你可以适应更复杂的情况

标签: r dataframe subtraction


【解决方案1】:

difftransform 一起使用:

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

产量:

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

作为 og dplyr

library(dplyr)

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

【讨论】:

    【解决方案2】:

    使用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
    

    【讨论】:

    • 如果 x 或 y 有一些 NA 怎么办?
    • @user3841581 - 同样的方法应该有效......不是吗?
    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 2021-02-03
    • 1970-01-01
    • 2020-09-17
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多