我在 R 中有这些数据框:
abc_1 <- data.frame(col1 = 1:5, col2 = 6:10, col3 = 11:15)
abc_2 <- data.frame(col1 = 21:25, col2 = 26:30, col4 = 31:35)
abc_3 <- data.frame(col1 = 41:45, col2 = 46:50, col5 = 51:55)
def_1 <- data.frame(col1 = 61:65, col2 = 66:70, col6 = 71:75)
对于以“abc_”开头的所有数据帧,我想识别与所有文件共享的列集,然后将它们绑定在一起。
我尝试长期这样做:
all_objects <- ls()
abc_objects <- all_objects[grep("^abc", all_objects)]
common_cols <- Reduce(intersect, lapply(abc_objects, function(x) colnames(get(x))))
combined_df <- do.call(rbind, lapply(abc_objects, function(x) {
df <- get(x)
df[, common_cols, drop = FALSE]
}))
有更直接的方法吗?
这是一个替代方案。我首先创建一个数据帧列表,然后可以对其进行绑定(
do.call(rbind...
不适用于不同的列名称)。
library(dplyr)
abc_objects <- do.call("list", mget(grep("^abc", names(.GlobalEnv), value = TRUE)))
bind_rows(abc_objects) |>
select(where(~ !any(is.na(.))))
#> col1 col2
#> 1 1 6
#> 2 2 7
#> 3 3 8
#> 4 4 9
#> 5 5 10
#> 6 21 26
#> 7 22 27
#> 8 23 28
#> 9 24 29
#> 10 25 30
#> 11 41 46
#> 12 42 47
#> 13 43 48
#> 14 44 49
#> 15 45 50