我有一个初始的value
以及三个数据集在一个列表中:
value <- 10
df1 <- data.frame(id = c("a", "b", "c"), quantity = c(3, 7, -2))
df2 <- data.frame(id = c("d", "e", "f"), quantity = c(0, -3, 9))
df3 <- data.frame(id = c("g", "h", "i"), quantity = c(-2, 0, 4))
df_list <- list(df1, df2, df3)
我想对列表中的每个数据帧应用多个函数,在操作结束时动态更新value
,然后在下一个列表项上运行相同的过程。挑战在于函数本身以value
作为输入。
# Example function 1: Generate `outcome` by multiplying quantity times a random number
df_list[[1]]$outcome <- df_list[[1]]$quantity * sample(1:10, 1)
# Example function 2: Multiply `value` by `quantity` to update `outcome`
df_list[[1]]$outcome <- value * df_list[[1]]$quantity
# Updates `value` by adding the old `value` to the sum of the outcome column:
value <- value + as.numeric(colSums(df_list[[1]]["outcome"]))
# Repeats operations for df_list[[2]] and df_list[[3]]
df_list[[2]]$outcome <- df_list[[2]]$quantity * sample(1:10, 1)
df_list[[2]]$outcome <- value * df_list[[2]]$quantity
value <- value + as.numeric(colSums(df_list[[2]]["outcome"]))
df_list[[3]]$outcome <- df_list[[3]]$quantity * sample(1:10, 1)
df_list[[3]]$outcome <- value * df_list[[3]]$quantity
value <- value + as.numeric(colSums(df_list[[3]]["outcome"]))
我可以使用lapply在每个列表项上运行函数,但是在继续到下一个列表项之前,我如何访问(并动态更新)非列表对象value
?
如果我们需要更新,使用for
循环,即在list
序列上循环并更改索引
for(i in seq_along(df_list)) {
# Multiplies `value` by `quantity` to obtain `outcome` for each row in df_list[[1]]
df_list[[i]]$outcome <- value * df_list[[i]]$quantity
# Updates `outcome` by multiplying by a random number
df_list[[i]]$outcome <- df_list[[i]]$quantity * sample(1:10, 1)
value <- value + as.numeric(colSums(df_list[[i]]["outcome"]))
}
与产出
> value
[1] 84