在遇到另一个问题后,我在思考这个问题。
library(tidyverse)
set.seed(42)
df <- data.frame(x = cut(runif(100), c(0,25,75,125,175,225,299)))
tidyr::extract
很好地将正则表达式定义的组进行了拆分:
df %>%
extract(x, c("start", "end"), "(\d+),(\d+)") %>% head
#> start end
#> 1 0 25
#> 2 0 25
#> 3 0 25
#> 4 0 25
#> 5 0 25
#> 6 0 25
字符矢量的所需输出。我知道你可以创建一个新的函数,我想知道这是否已经存在了。
x_chr <- as.character(df$x)
des_res <- str_split(str_extract(x_chr, "(\d+),(\d+)"), ",")
head(des_res)
#> [[1]]
#> [1] "0" "25"
#>
#> [[2]]
#> [1] "0" "25"
#>
#> [[3]]
#> [1] "0" "25"
#>
#> [[4]]
#> [1] "0" "25"
#>
#> [[5]]
#> [1] "0" "25"
#>
#> [[6]]
#> [1] "0" "25"
您可以在基本R:中使用strcapture
strcapture("(\d+),(\d+)", x_chr,
proto = list(start = numeric(), end = numeric()))
# start end
#1 0 25
#2 0 25
#3 0 25
#4 0 25
#5 0 25
#6 0 25
#...
#...
您也可以使用stringr::str_match
:
stringr::str_match(x_chr, "(\d+),(\d+)")[, -1]
在str_match
中,第一列返回完整模式,而所有后续列都是捕获组。