您可以使用循环来重复 cbind 函数吗?

问题描述

我有两个数据帧(增长和投资),我使用 group_split() 函数将它们拆分为 40 个数据帧(按荷兰的 COROP 区域拆分)。我的目标是合并每个 COROP 的拆分数据帧,这可以使用以下代码完成:

# COROP 1
CR01 <- cbind(growth_per_corop[[1]],investment_per_corop[[1]]) # merging growth and investment data for corop 1
CR01 <- CR01[-c(4:6)] # removing duplicate columns
# COROP 2
CR02 <- cbind(growth_per_corop[[2]],investment_per_corop[[2]]) # merging growth and investment data for corop 2
CR02 <- CR02[-c(4:6)] # removing duplicate columns

我的问题是,为 COROP 1 到 40 手动重复此操作需要很长时间,但我对循环的了解非常有限,我想知道是否有人可以帮助我。是否可以使用循环重复上面的代码来创建从 1 到 40 的新合并数据帧?

谢谢!

解决方法

我们可以使用map2

library(dplyr)
library(purrr)
map2_dfr(growth_per_corop,investment_per_corop,cbind) %>%
           select(-(4:6))

或者使用 Map 中的 base R

do.call(rbind,Map(cbind,growth_per_corop,investment_per_corop))[-c(4:6)]
,

使用传统的 for 循环:(不如 map/apply 方法有效)

n_df <- 40
data_merged <- vector('list',n_df) #empty list with length 40

for (i in 1:n_df) {
    data_merged[[i]] <- cbind(growth_per_corop[[i]],investment_per_corop[[i]]) %>% 
                          select(-(4:6))
}

#optionally combine everything back again
purrr::reduce(data_merged,cbind)