【问题标题】:Extracting substring by positions in pipe按管道中的位置提取子串
【发布时间】:2020-06-04 09:03:39
【问题描述】:

我想从小标题的id 列的每一行中提取子字符串。我总是对原始id 的第一和第三空间之间的区域感兴趣。生成的子字符串,所以 Zoe BostonJane Rome,将进入新列 - name

我尝试使用str_locate_all 获取每个id 中“空格”的位置,然后使用位置来使用str_sub。但是我无法正确提取位置。

data <- tibble(id = c("#1265746 Zoe Boston 58962 st. Victory cont_1.0)", "#958463279246 Jane Rome 874593.01 musician band: XYZ 985147") ) %>% 
   mutate(coor =  str_locate_all(id, "\\s"),
   name = str_sub(id, start = coor[[1]], end = coor[[3]] ) )

【问题讨论】:

    标签: r dplyr stringr


    【解决方案1】:

    您可以使用正则表达式来提取您想要的内容。

    假设您已将 tibble 存储在 data,您可以使用 sub 提取第一个和第二个单词。

    sub('^#\\w+\\s(\\w+\\s\\w+).*', '\\1', data$id)
    #[1] "Zoe Boston" "Jane Rome" 
    

    ^# - 以哈希开头

    \\w+ - 一句话

    \\s - 空格

    ( - 捕获组的开始

    \\w+ - 一句话

    后跟\\s - 空格

    \\w+ - 另一个词

    ) - 捕获组结束。

    .* - 剩余字符串。


    str_locate 更复杂,因为它首先返回空格的位置,然后您需要选择第一个空格的结尾和第三个空格的开头,然后使用str_sub 提取这些位置之间的文本。

    library(dplyr)
    library(stringr)
    library(purrr)
    
    data %>%
       mutate(coor =  str_locate_all(id, "\\s"), 
              start = map_dbl(coor, `[`, 1) + 1, 
              end = map_dbl(coor, `[`, 3) - 1,
              name = str_sub(id, start, end))
    
    # A tibble: 2 x 2
    #  id                                                          name      
    #  <chr>                                                       <chr>     
    #1 #1265746 Zoe Boston 58962 st. Victory cont_1.0)             Zoe Boston
    #2 #958463279246 Jane Rome 874593.01 musician band: XYZ 985147 Jane Rome 
    

    【讨论】:

    • 你能解释一下后面的regex吗?
    • 添加说明。
    【解决方案2】:

    使用stringrpurrr 包的另一种可能解决方案

    library(stringr)
    library(purrr)
    library(dplyr)
    
    data %>%
      mutate(name = map_chr(str_split(id, " "), ~paste(unlist(.)[2:3], collapse = " ")))
    

    解释:

    • str_split(id, " ") 中,我们创建了一个在id 中用空格分隔的术语列表
    • map_chr 可用于获取这些列表中的每一个,并对它们应用以下功能:取消列表,获取位置 2 和 3 的元素(这是我们想要的 name),然后用空格折叠它们他们之间

    输出

    # A tibble: 2 x 2
    #   id                                                          name      
    #   <chr>                                                       <chr>     
    # 1 #1265746 Zoe Boston 58962 st. Victory cont_1.0)             Zoe Boston
    # 2 #958463279246 Jane Rome 874593.01 musician band: XYZ 985147 Jane Rome 
    

    【讨论】:

      猜你喜欢
      • 2014-12-10
      • 2021-01-23
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      相关资源
      最近更新 更多