循环中的 cbind 数据帧

cbind dataframes in loop

我有 n 个名为 "s.dfx" 的数据帧,其中 x=1:n。所有数据框都有 7 列,名称不同。现在我想绑定所有数据帧。

我知道命令

t<-cbind.data.frame(s.df1,s,df2,...,s.dfn)

但我想优化并循环绑定它们,因为 n 是一个很大的数字。

我试过了

for(t2 in 1:n){ t<-cbind.data.drame(s.df[t2]) }

但是我得到这个错误"Error in [.data.frame(s.df, t2) : undefined columns selected"

有人能帮忙吗?

library(purrr) #to be redundant

#generating dummy data frames
df1 <- data.frame(x = c(1,2),      y = letters[1:2])
df2 <- data.frame(x = c(10,20),    y = letters[c(10, 20)])
df3 <- data.frame(x = c(100, 200), y = letters[c(11, 22)])

#' DEMO [to be adapted]: capturing the EXAMPLE data frames in a list
dfs <- mget(ls(pattern = "^df[1-3]"))

#A Tidyverse (purrr) Solution
t <- purrr::reduce(.x = dfs, .f = bind_cols)

#Base R
do.call(cbind,dfs)  
# or
Reduce(cbind,dfs)

我认为 for-loop 不会比 do.call(cbind, dfs) 快,但我不清楚您是否真的有这样一个列表。我认为您可能需要从角色对象构建这样的列表。此答案假设您还没有列表,但您确实已将所有数据帧按升序编号,并以 n 结尾,其中十进制表示可能有多个数字。

 t <- do.call( cbind, mget( paste0("s.dfs", 1:n) ) )

Pasqui 在 mget 中使用 ls 和一个模式来捕获所有编号的数据帧。我会使用稍微不同的一个,因为你建议数字大于 9,这是他的模式将捕获的所有内容:

  ls(pattern = "^s\.df[0-9]+")  # any number of digits
                # ^ need double escapes to make '.' a literal period or fixed=TRUE