我有以下数据框:
library(tidyverse)
dat <-structure(list(motif_name_binned = c("Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1",
"Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2",
"Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3"
), motif_score = c(6.816695, 6.816695, 6.816695)), row.names = c(NA,
-3L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("motif_name_binned",
"motif_score"))
dat
这给出了这个:
> dat
# A tibble: 3 x 2
motif_name_binned motif_score
<chr> <dbl>
1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1 6.816695
2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2 6.816695
3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3 6.816695
我可以通过使用以下代码提取motif_named_binned
的值来获得我想要的内容:
dat %>%
mutate(motif = str_match(motif_name_binned,"^(.*?)\\/.*?")[,2],
inst = str_match(motif_name_binned,"^.*?\\/.*?\\/.*?\\.instid_(.*?)\\.bin\\d+")[,2],
binno = as.integer(str_match(motif_name_binned,"^.*?\\/.*?\\/.*?\\.bin(\\d+)")[,2]))
哪个给出了
# A tibble: 3 x 5
motif_name_binned motif_score motif inst binno
<chr> <dbl> <chr> <chr> <int>
1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1 6.816695 Ddit3::Cebpa chr1:183286845-183287245 1
2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2 6.816695 Ddit3::Cebpa chr1:183286845-183287245 2
3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3 6.816695 Ddit3::Cebpa chr1:183286845-183287245 3
但请注意,我必须执行正则表达式3次并将其逐个分配给变量。事实上,我可以使用单一的正则表达式:
str_match(motif_name_binned,"^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)")[,c(2,3,4)]
我如何在dplyr mutate()
中合并后来的一体化正则表达式?
答案 0 :(得分:4)
您可以使用tidyr::extract
将正则表达式中的捕获组转换为新列:
library(tidyr)
dat %>%
extract(motif_name_binned, c('motif', 'inst', 'binno'), regex = "^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)", remove = FALSE)
# A tibble: 3 x 5
# motif_name_binned motif inst binno motif_score
#* <chr> <chr> <chr> <chr> <dbl>
#1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1 Ddit3::Cebpa chr1:183286845-183287245 1 6.816695
#2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2 Ddit3::Cebpa chr1:183286845-183287245 2 6.816695
#3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3 Ddit3::Cebpa chr1:183286845-183287245 3 6.816695