1

I have two dataframes (growth and investment) that I have split using the group_split() function into 40 dataframes (split per COROP region in the Netherlands). My aim is to merge the split dataframes for each COROP, which can be done using the following code:

# 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

etc.

My issue is that to repeat this manually for COROP 1 to 40 takes really long, but my knowledge of loops is very limited and I was wondering if anybody could help me. Is it possible to use a loop to repeat the code above to create new merged dataframes from 1 to 40?

Thanks!

2 Answers2

0

We can use map2

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

Or using Map from base R

do.call(rbind, Map(cbind, growth_per_corop, investment_per_corop))[-c(4:6)]
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Using a traditional for loop: (not as efficient as map/apply approach)

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)
jpdugo17
  • 6,816
  • 2
  • 11
  • 23