【问题标题】:How to subtract a row from the row above using a for loop in R?如何使用R中的for循环从上面的行中减去一行?
【发布时间】:2019-11-25 10:13:03
【问题描述】:

我正在尝试学习如何在 R 中使用 for 循环,特别是从 R 中一列中的上述数字中减去一个数字。

我知道可以使用 b <- diff(df$a) 或使用:

library(dplyr)
df %>% 
  mutate(b = a - lag(a)) 

但我试图了解如何通过以下方式获得相同的结果:

for(i in 1:nrow(df)){
  result = df[2,] - df[i,]
  print (result)
}

如何设置这个 for 循环,以便 df[2,] 获取后面的每一行,而不仅仅是第二行,并从上面的行中减去?

例如我有这样的数据:

column a
1
10
20 

我想最终创建一个带有减法的列:

column a    column b
1             10
11            9
20           ...

【问题讨论】:

    标签: r for-loop dplyr


    【解决方案1】:

    你可以使用for循环喜欢

    df$columnB <- NA
    
    for(i in 1:(nrow(df) - 1)) {
       df$columnB[i] = df$columnA[i+1] - df$columnA[i]
    }
    df
    #  columnA columnB
    #1       1      10
    #2      11       9
    #3      20       5
    #4      25       9
    #5      34      NA
    

    数据

    使用的样本数据:

    df <- data.frame(columnA  =  c(1, 11, 20, 25, 34))
    

    【讨论】:

    • 这是完美的,我现在明白它是如何在循环中工作的,谢谢! (只要允许我就点击勾号)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多