在遇到另一个问题后我正在思考这个问题。
library(tidyverse)
set.seed(42)
df <- data.frame(x = cut(runif(100), c(0,25,75,125,175,225,299)))
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
字符向量上的所需输出。我知道你可以创建一个新函数,我想知道这是否已经存在。
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"
Run Code Online (Sandbox Code Playgroud)
strcapture您可以在基础 R 中使用:
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
#...
#...
Run Code Online (Sandbox Code Playgroud)
您还可以使用stringr::str_match:
stringr::str_match(x_chr, "(\\d+),(\\d+)")[, -1]
Run Code Online (Sandbox Code Playgroud)
在 中str_match,第一列返回完整模式,而所有后续列都是捕获组。