【问题标题】:How to merge two dataframes in R based on a matching part of a string?如何根据字符串的匹配部分合并 R 中的两个数据框?
【发布时间】:2021-07-27 17:06:39
【问题描述】:

我有两个数据框,一个包含各个国家/地区的经济信息,另一个包含国家/地区的专有名称。两个数据框如下所示:

country <- c("Afghanistan", "Afghanistan", "United States", "United States", "Congo, Dem. Rep.", "Congo, Dem. Rep.", "Middle East and North Africa", "Middle East and North Africa")
years <- c(2011, 2012, 2011, 2012, 2011, 2012, 2011, 2012)
gdp <- c(123, 442, 9451, 9999, 351, 664, 7531, 6634)
economic_data <- cbind.data.frame(country, years, gdp)

country_proper <- c("Afghanistan", "United States of America", "Congo DR")

我想将economic_data 中的国家名称更改为country_proper 数据中的专有名称,然后删除经济数据中没有出现在country_proper 中的国家(如“中东和北非”)。

【问题讨论】:

    标签: r dplyr tidyverse gsub


    【解决方案1】:

    您需要使用模糊匹配。试试这个 -

    country <- c("Afghanistan", "Afghanistan", "United States", "United States", "Congo, Dem. Rep.", "Congo, Dem. Rep.", "Middle East and North Africa", "Middle East and North Africa")
    years <- c(2011, 2012, 2011, 2012, 2011, 2012, 2011, 2012)
    gdp <- c(123, 442, 9451, 9999, 351, 664, 7531, 6634)
    economic_data <- data.frame(country, years, gdp, stringsAsFactors = F)
    
    country_proper <- c("Afghanistan", "United States of America", "Congo DR")
    country_proper <- data.frame(country = country_proper, stringsAsFactors = F)
    
    library(fuzzyjoin)
    stringdist_join(economic_data, 
                    country_proper,
                    method = c("soundex"),
                    mode = "inner",
                    by = "country") 
    

    【讨论】:

      【解决方案2】:

      这是另一种方法: 我们可以使用来自stringr 包的str_replace_all

      library(dplyr)
      library(stringr)
      economic_data %>% 
          mutate(country = str_replace_all(country, c(
              "^United States$" = "United States of America",
              "^Congo, Dem. Rep.$" = "Congo DR")))
      

      数据:

                             country years  gdp
      1                  Afghanistan  2011  123
      2                  Afghanistan  2012  442
      3     United States of America  2011 9451
      4     United States of America  2012 9999
      5                     Congo DR  2011  351
      6                     Congo DR  2012  664
      7 Middle East and North Africa  2011 7531
      8 Middle East and North Africa  2012 6634
      

      【讨论】:

        猜你喜欢
        • 2016-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-25
        相关资源
        最近更新 更多