【发布时间】: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