通过管道中的位置提取子字符串

问题描述 投票:0回答:2

我想从小标题的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
2个回答
1
投票

您可以使用正则表达式提取所需的内容。

假设您已将小标题存储在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 

0
投票

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

library(stringr)
library(purrr)
library(dplyr)

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

输出

# 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 
© www.soinside.com 2019 - 2024. All rights reserved.