【问题标题】:join variable with variable in which many data contains in row in R将变量与其中许多数据包含在R中的行中的变量连接起来
【发布时间】:2020-06-12 09:35:50
【问题描述】:

我想执行加入。

df1=structure(list(id = 1:3, group_id = c(10L, 20L, 40L)), class = "data.frame", row.names = c(NA, 
-3L))

df2 有另一个结构,在 group_id 的字段中包含许多组。例如{10,100,400} 所以dput()

df2=structure(list(id = 1:3, group_id = structure(c(1L, 3L, 2L), .Label = c("{`10`,100,`40`}", 
"{3,`40`,600,100}", "{4}"), class = "factor")), class = "data.frame", row.names = c(NA, 
-3L))

df2 有 group_id 1040,但它们与其他组一起用大括号括起来。 如何获得所需的连接输出

id  group_id
1   10
1   40
3   40

【问题讨论】:

    标签: r dplyr data.table


    【解决方案1】:

    您可以使用gsub 清理df2 中的group_id,将每个ID 放在单独的行中,然后filter

    library(dplyr)
    
    df2 %>%
      mutate(group_id = gsub('[{}`]', '', group_id)) %>%
      tidyr::separate_rows(group_id) %>%
      filter(group_id %in% df1$group_id)
    
    #  id group_id
    #1  1       10
    #2  1       40
    #3  3       40
    

    【讨论】:

      【解决方案2】:

      这是data.table 替代方案:

      df2[, strsplit(gsub('[{}`]', '', group_id), ','), by = id][V1 %in% df1$group_id]
      #   id V1
      #1:  1 10
      #2:  1 40
      #3:  3 40
      

      【讨论】:

        【解决方案3】:

        这是base R 使用regmatches/regexpr 的选项

        subset(setNames(stack(setNames(regmatches(df2$group_id, gregexpr("\\d+", df2$group_id)),
              df2$id))[2:1], c('id', 'group_id')), group_id %in% df1$group_id)
        #  id group_id
        #1  1       10
        #3  1       40
        #6  3       40
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-25
          • 1970-01-01
          • 1970-01-01
          • 2014-12-13
          相关资源
          最近更新 更多