【发布时间】:2021-02-18 00:50:22
【问题描述】:
我正在做一些模拟,并且我有几个数据框,它们的列存储在一个列表中。对于每个数据帧,我想创建一个新变量,该变量具有之前 2 个数据帧(和当前数据帧)中每一行的平均值。我在制定循环时遇到问题。这是一个可重现的示例:
#Create dataframe
month <- 1:12
price <- 21:32
df <- data.frame(month, price)
#Separate each row and create a simulation of a new variable. Store new dataframes in a list
simulations <- 100
ints <- seq_len(12)
set.seed(96)
list <- lapply(setNames(ints, paste0("df", ints)), function(i) {
cbind(
df[rep(i, simulations),],
q = as.numeric(runif(simulations, min = 5, max = 10)))
})
#for each df in list, calculate the mean of the last 3 values of q
for (i in 3:length(list)) {
list[[i]][["q_mean"]] <- mean(list[[(i-2):i]][["q"]]) #HERE IS THE PROBLEM
list[[i]][["ben"]] <- list[[i]][["q_mean"]]*list[[i]][["price"]]
}
我收到“列表错误 [[(i - 2): i]] [["q"]]: subscript out of bounds”。有谁知道可能是什么问题?提前致谢!
【问题讨论】:
-
看起来@redarah 让你走在了正确的道路上,但还有一条评论——我会避免命名一个新对象
list,因为 R 中已经存在具有该名称的东西,它可能会导致其他地方的意外行为。