【问题标题】:extract substring from string given in list从列表中给出的字符串中提取子字符串
【发布时间】:2019-04-30 15:38:00
【问题描述】:

我有两个小标题,一个带有一些长度不均匀的系列代码,一个带有国家/地区代码

codes <- as.tibble(c("brcomec", "frcomopf", "decombwf", "ezcomop", 
       "jpcomop", "aewheob", "ezcompis", "decomipf"))
countries <- as.tibble(c("br", "fr", "advecos", "af", "africa", "al", "dz", "as", "ad", 
                     "ao", "ai", "aq", "ag"))

根据国家/地区的信息,我如何从“代码”中提取国家/地区,即我希望有类似的东西

dta <- data.frame( 
~country , ~ rest , 
br       , comec  ,
fr       , comopf ,
...
) 

我尝试使用 filter(str_detect(code, paste(countries))) 但这没有成功,因此非常感谢任何帮助。

【问题讨论】:

    标签: r filter dplyr tidyverse stringr


    【解决方案1】:

    你想要这样的东西吗?

    library(tidyverse)
    codes1 <- substr(codes$value, start = 1, stop = 2)
    codes2 <- substr(codes$value, start = 3, stop = 10)
    
    codes3 = tibble(codes1, codes2)
    codes3
    

    哪个返回这个?

    # A tibble: 8 x 2
      codes1 codes2
      <chr>  <chr> 
    1 br     comec 
    2 fr     comopf
    3 de     combwf
    4 ez     comop 
    5 jp     comop 
    6 ae     wheob 
    7 ez     compis
    8 de     comipf
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      相关资源
      最近更新 更多