【问题标题】:same merge in for loop instead of repeating the code在 for 循环中进行相同的合并,而不是重复代码
【发布时间】:2021-06-23 04:11:29
【问题描述】:

如何进行以下操作:

df_2 <- merge(df_2, df_1[,c("id","x_2")], by = "id", all.x = T)
df_3 <- merge(df_3, df_1[,c("id","x_3")], by = "id", all.x = T)
df_4 <- merge(df_4, df_1[,c("id","x_4")], by = "id", all.x = T)

在 for 循环中,而不是重复相同的代码行?

【问题讨论】:

  • 为什么不只是merge(df_2, df_1[,c("id","x_2", "x_3","x_4")], by = "id", all.x = T)
  • 您的 df_1、df_2、df_3 和 df_4 是什么样的?请分享其中的几行
  • 因为我只在df_2中需要x_2,在df_3中只需要x_3等等。我需要将dfs分开

标签: r loops merge


【解决方案1】:

使用 getassign ,如下所示:


for( i in 2:4 ) {

  x_name <- paste0( "x_",  i+1 )
  d_name <- paste0( "df_", i+1 )
  
  df_i <- get(d_name)
  assign( d_name, merge( df_i, df_1[, c("id",x_name)], by="id", all.x = TRUE )

}

【讨论】:

    【解决方案2】:

    我们可以使用Map():

    Map(function(df, x){
      merge(df, df_1[,c("id",x)], by = "id", all.x = T)
    },
    list(df_2, df_3, df_4),
    c("x_2", "x_3", "x_4"))
    

    这将为您提供所需更新的 data.frame()s 列表,但我建议无论如何处理列表中的多个类似 dfs,这样可以保持内容相当整洁。

    【讨论】:

      【解决方案3】:

      我看到 Sirius 已经涵盖了它,但我的答案是这样写的,所以你去吧(一些小的差异):)

      df_1 <- data.table(id=1, x_2=2, x_3=3, x_4=4)
      df_2 <- data.table(id=1)
      df_3 <- data.table(id=1)
      df_4 <- data.table(id=1)
      
      indexes <- 2:4
      
      for(i in indexes){
        df_to_update <- sprintf("df_%s", i)
        df_temp <- merge(get(df_to_update), 
                         df_1[,c("id", sprintf("x_%s", i)), with=FALSE],
                         by="id", all.x=TRUE)
        assign(df_to_update, df_temp, envir = .GlobalEnv)
      }
      
      df_2[]
      df_3[]
      df_4[]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-14
        • 1970-01-01
        • 2014-01-11
        • 2020-11-19
        • 1970-01-01
        • 2019-07-27
        • 1970-01-01
        相关资源
        最近更新 更多