在我的数据中,有一列打开的文本字段数据类似于以下示例:
d <- tribble(
~x,
"i am 10 and she is 50",
"he is 32 and i am 22",
"he may be 70 and she may be 99",
)
我想使用regex
将所有两位数字提取到新列y
中。我有以下代码,在提取第一个匹配项时效果很好:
d %>%
mutate(y = str_extract(x, "([0-9]{2})"))
# A tibble: 3 x 2
x y
<chr> <chr>
1 i am 10 and she is 50 10
2 he is 32 and i am 22 32
3 he may be 70 and she may be 99 70
但是,是否可以使用某些标准分隔符(例如逗号)将两个两位数字都提取到同一列中?
我们可以使用str_extract_all
而不是str_extract
,因为str_extract
仅与第一个实例匹配,因为_all
后缀是全局的,并且会提取list
中的所有实例,可以将它们转换回两个unnest_wider
library(dplyr)
library(tidyr)
library(stringr)
d %>%
mutate(out = str_extract_all(x, "\\d{2}")) %>%
unnest_wider(c(out))