【问题标题】:Can you use a loop to repeat a cbind function?您可以使用循环来重复 cbind 函数吗?
【发布时间】:2021-05-30 20:39:11
【问题描述】:

我使用 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 的新合并数据帧?

谢谢!

【问题讨论】:

    标签: r loops cbind


    【解决方案1】:

    我们可以使用map2

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

    或者使用来自base RMap

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

    【讨论】:

      【解决方案2】:

      使用传统的 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-29
        • 1970-01-01
        相关资源
        最近更新 更多