【问题标题】:How to merge data frames where column1 is substring of column2如何合并column1是column2子串的数据框
【发布时间】:2017-10-05 10:11:56
【问题描述】:

我有一个数据框,想根据列 df$name 的值对每一行进行分类。对于分类,我有一个两列数据框 tl,其中有一列 tl$name 和 tl$type。我想在类似的条件下合并两个数据框,grepl(tl$name, df$name),而不是 df$name = tl$name。

我已经尝试循环遍历 df 中的所有行并查看与 tl 匹配的位置,但这似乎非常耗时。

例如:

df

  name        
# African elephant    
# Indian elephant    
# Silverback gorilla     
# Nile crocodile   
# White shark       

tl

  name        type
# elephant    mammal
# gorilla     mammal
# crocodile   reptile
# shark       fish

【问题讨论】:

    标签: r dataframe merge


    【解决方案1】:
    df
    
      name        
    # African elephant    
    # Indian elephant    
    # Silverback gorilla     
    # Nile crocodile   
    # White shark       
    tl
    
      name        type
    # elephant    mammal
    # gorilla     mammal
    # crocodile   reptile
    # shark       fish
    

    我认为这就是你想要做的

    df<-csplit(df, splitcols="name", sep=" ")
    

    上面的命令会将该列拆分为两列,分别为 name.1 和 name.2 列名。

    colnames(df)<-c("name","type")
    

    上面的命令会给出正确的合并列名

    df_tl<-merge(x=df, y=tl, by="type",all=True)
    

    上面的代码应该会给你想要的输出。

    【讨论】:

      【解决方案2】:

      另一个想法:

      library(tidyverse)
      
      df %>%
        separate(name, into = c("t", "name")) %>%
        left_join(tl)
      

      这给出了:

      #           t      name    type
      #1    African  elephant  mammal
      #2     Indian  elephant  mammal
      #3 Silverback   gorilla  mammal
      #4       Nile crocodile reptile
      #5      White     shark    fish
      

      【讨论】:

      • 感谢您的回复。如果有两个空格会发生什么,例如南美蜥蜴?名称会在第一个空格还是第二个空格分开?
      【解决方案3】:

      我们可以通过匹配一个或多个非空白 (\\S+) 后跟一个或多个空白 (\\s+) 从字符串的开头 (^) 来删除带有 sub 的子字符串,将其替换为空白 ("") 并将 merge 替换为第二个数据集 ('tl')

      merge(transform(df, name = sub("^\\S+\\s+", "", name)), tl)
      #      name    type
      #1 crocodile reptile
      #2  elephant  mammal
      #3  elephant  mammal
      #4   gorilla  mammal
      #5     shark    fish
      

      如果我们需要更新第一个数据集,

      df$type <- with(df, tl$type[match(sub("^\\S+\\s+", "", name), tl$name)])
      

      【讨论】:

      • 谢谢。如果子字符串是字符串的开头怎么办,例如大象非洲?
      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2021-02-23
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多