简体   繁体   English

如何制作一个循环以从 1000 个数据帧中获取一个变量

[英]how to make a loop to fetch one variable from 1000 dataframes

I have dataframe by name V1...V1000.我有 dataframe 的名字 V1...V1000。 inside the dataframe each has one variable with the same name 'var1.predict'.在 dataframe 中,每个变量都有一个同名“var1.predict”的变量。 I'm having a hard time creating a loop in order to concatenate all the variables I want to fetch into one new dataframe我很难创建一个循环,以便将我想要获取的所有变量连接到一个新的 dataframe 中

this is the syntax I want to make a loop这是我想要循环的语法

df <- cbind.data.frame(model_V1$var1.pred,model_V2$var1.pred,.....model_V1000$var1.pred)

I hope someone can help solve this.我希望有人可以帮助解决这个问题。 thank you谢谢你

a new dataframe formed by taking one variable from each dataframe通过从每个 dataframe 中取一个变量形成一个新的 dataframe

I assume that you mean you have 1,000 dataframes V1... V1000 each with the column var1.predict and you want to extract the predictions column from each df.我假设您的意思是您有 1,000 个数据帧 V1...V1000,每个数据帧都有var1.predict列,并且您想从每个 df 中提取预测列。 If so, there are a few methods outlined below with a little reprex:如果是这样,下面列出了一些带有一点代表的方法:

# putting dummy data in to the global env
lapply(1:3, \(i) {
  assign(paste0("V", i), data.frame(v1 = rnorm(5), 
                                    v2 = rnorm(5), 
                                    var1.predict = rnorm(5)), envir = .GlobalEnv)
})

df_list <- list(V1, V3, V3)

# using a for loop and do.call
pred_cols <- list()
for (df in df_list) {
  pred_cols <- c(pred_cols, list(df[["var1.predict"]]))
}
pred_cols_df <- do.call(cbind, pred_cols) 
as.data.frame(pred_cols_df)
pred_cols_df


# using a loop without do.call
for (i in seq_along(df_list)) {
  if (i == 1) {
    pred_cols_df <- df_list[[1]][["var1.predict"]]
  } else {
    pred_cols_df <- cbind(pred_cols_df, df_list[[i]][["var1.predict"]])
  }
}
as.data.frame(pred_cols_df)
pred_cols_df

# using lapply
pred_cols <- lapply(df_list, `[`, "var1.predict")
pred_cols_df <- do.call(cbind, pred_cols)
as.data.frame(pred_cols_df)
pred_cols_df

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM