我正在做一些模拟,并且我有几个具有相同列的数据框存储在列表中。对于每个数据框,我想创建一个新变量,该变量具有之前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”]]:下标超出范围”。有谁知道可能是什么问题?提前致谢!
我注意到有两件事在这里给您带来麻烦:
1-当您像list[[1:3]]
这样对列表进行子集设置时,将其读取为list[[c(1, 2, 3)]]
,并在列表的第一个元素(df1)中找到第二列(价格)的第三个条目(21)。这就是为什么执行list [1:2]之类的操作会返回一个向量(它提取出一个完整的变量)的原因,以及为什么list [1:4]会返回一个错误(列表的深度未达到4级)的原因。(通过评论@ aaron-montgomery回答)
2-在最后一行中,引用了mean
从未定义的列。
如果要获取一个值,该值是所有先前元素的平均值,则可以嵌套另一个循环:
#for each df in list, calculate the mean of the last 3 values of q
for (i in 3:length(list)) {
# add another loop to calculate the mean
vals <- c()
for (j in (i - 2):i) {
vals <- c(vals, list[[j]]$q)
}
list[[i]][["q_mean"]] <- mean(vals)
}
如果您希望每行使用不同的值(其中row1是前两个row1的平均值,等等),则可以执行以下操作:
for (i in 3:length(list)) {
list[[i]][["q_mean"]] <- (list[[i - 1]]$q + list[[i - 2]]$q) /2
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句