【问题标题】:Match two tables's columns when the elements are separated by slash当元素用斜线分隔时匹配两个表的列
【发布时间】:2021-11-05 10:32:52
【问题描述】:

我有一个如下所示的数据框:

Names Identification
Animals 15/20/25/26
Fruits 1/2/3/4

还有一个看起来像这样的数据框:

Id Identification
Cat 15
Dog 20
Elephant 25
Mouse 26
Banana 1
Melon 2
Mango 3
Apple 4

我想将第一个表中的标识码匹配到第二个表中以在原始表中创建一个新列:

Names Identification Id
Animals 15/20/25/26 Cat/Dog/Elephant/Mouse
Fruits 1/2/3/4 Banana/Melon/Mango/Apple

这是表格的代码:


original <- data.frame(
    Names = c('Animals', 'Fruits'),
    Identification = c('15/20/25/26', '1/2/3/4')
)


to_match <- data.frame(
    Id = c('Cat', 'Dog', 'Elephant', 'Mouse','Banana', 'Melon', 'Mango','Apple'),
    Identification = c(15,20,25,26,1,2,3,4)
)

这是我尝试过的,由于斜线而不起作用。

original$Id <- to_match$Id[match(original$Identifcation, to_match$Identification),]
    

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: r dplyr match stringr


    【解决方案1】:

    您可以使用separate_rows,然后再次分组:

    library(tidyverse)
    
    a <- read.table(text = "Names   Identification
    Animals 15/20/25/26
    Fruits  1/2/3/4", header = T)
    
    b <- read.table(text = "Id  Identification
    Cat 15
    Dog 20
    Elephant    25
    Mouse   26
    Banana  1
    Melon   2
    Mango   3
    Apple   4", header = T)
    
    a %>%
      separate_rows(Identification) %>%
      left_join(b %>%
                  mutate_all(as.character), by = "Identification") %>%
      group_by(Names) %>%
      summarise(Identification = str_c(Identification, collapse = "/"),
                Id = str_c(Id, collapse =  "/"), 
                .groups = "drop")
    
    # # A tibble: 2 x 3
    # Names   Identification Id                      
    # <chr>   <chr>          <chr>                   
    #   1 Animals 15/20/25/26    Cat/Dog/Elephant/Mouse  
    # 2 Fruits  1/2/3/4        Banana/Melon/Mango/Apple
    

    【讨论】:

    • 谢谢!由于简单和速度,我会接受另一个答案。
    【解决方案2】:

    stringi 有一个函数可以让你做到这一点:

    original$Id <- stri_replace_all_fixed(original$Identification, to_match$Identification, to_match$Id, vectorize_all = F)
    

    【讨论】:

    • 哇,我从来没有见过这么快的函数。感谢您向我介绍这个包裹。完美运行。
    猜你喜欢
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多