试试这个:
# three toy dataframe
df1 <- data.frame(x = c(1:10))
df2 <- data.frame(x = c(11:20))
df3 <- data.frame(x = c(21:30))
# make a list
dfl <- list(df1, df2, df3)
# add "castigoex" to each df
for (i in 1:length(dfl)) {
dfl[[i]]$castigoex <- runif(10, 0, 1)
}
# I advise you to keep the dataframes in the list,
# but if you want to split them again
list2env(setNames(dfl, paste0("df", seq_along(dfl))), envir = parent.frame())
如果要避免for循环,可以使用mapply
new_list <- mapply(function(x) "[<-"(x, "castigoex", value = runif(10, 0, 1)),
dfl, SIMPLIFY = FALSE)
# now you have old list and new list. To split the list (with new name for df)
list2env(setNames(new_list,paste0("df_new", seq_along(new_list))),
envir = parent.frame())
如果要添加多于一列,一种可能的解决方案是使用lapply 函数
new_list2 <- lapply(dfl, function(x) cbind(x, castigoex = runif(10, 0, 1),
variable2 = runif(10, 0, 1)))
list2env(setNames(new_list2, paste0("df", seq_along(dfl))), envir = parent.frame())