【问题标题】:Using for-loops along a data frame column when defining a function in R在 R 中定义函数时沿数据框列使用 for 循环
【发布时间】:2018-01-17 18:19:41
【问题描述】:

我想定义一个函数,该函数将新列添加到数据框中,并通过循环现有列的条目来计算其条目。它应始终从下一行的条目中减去当前行的条目。新列应称为y

example_df <- data.frame(x = runif(10))
fun <- function(df, a, b) {
  df[, b] <- rep(NA, length(df[, a]))
  for (i in 1:(length(df[, a]) - 1)) {
    df[, b[[i]]] <- df[, a[[i + 1]]] - df[, a[[i]]]
  }
  return(df)
}

fun(example_df, "x", "y")

这将返回带有新 b 列的数据框,其中包含除最后一行之外的所有行的计算条目,应为 NA。 但是,我收到以下消息:

Error in a[[i + 1]] : subscript out of bounds
Called from: `[.data.frame`(df, , a[[i + 1]])

我无法找出问题所在,但猜测索引无法正常工作。感谢您提供的所有帮助!

【问题讨论】:

    标签: r function for-loop dataframe calculated-columns


    【解决方案1】:

    您不需要 for 循环来执行此操作。您可以使用 dplyr 包中的 mutatelead 函数:

    library(dplyr)
    set.seed(1234)
    
    example_df <- data.frame(x = runif(10))
    
    example_df %>% 
      mutate(y = lead(x, 1) - x)
    

    这会给你这个:

               x          y
    1  0.3873464  0.2171617
    2  0.6045081  0.3849549
    3  0.9894630 -0.1876334
    4  0.8018296 -0.3385969
    5  0.4632327 -0.2864295
    6  0.1768032  0.5489654
    7  0.7257686 -0.2135999
    8  0.5121687  0.4478171
    9  0.9599858 -0.5048904
    10 0.4550954         NA
    

    【讨论】:

    • 哇,这很简单,非常感谢!我绝对应该仔细研究一下 dplyr 包。
    猜你喜欢
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2015-05-14
    • 2020-03-14
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多