小编Gen*_*Rus的帖子

dplyr 中的快速字符串计数

我需要对小标题中的列中保存的字符串中的模式(固定)实例进行计数。mutate(x = str_count(col, pattern))正是我想要的,但它的速度不够快,无法处理我必须评估的字符串量。

简化的小标题

test = tibble(
  id=c(1,2,3),
  seq=c("ATCG","ATTT","CGCG")
)
Run Code Online (Sandbox Code Playgroud)

有效,但在微基准测试中速度太慢

test %>% mutate(CpG = str_count(seq, "CG"))
Run Code Online (Sandbox Code Playgroud)

理论上在单个序列上更快,但在我的 tibble 列上不起作用

这只是给出第一行计数的单个值

test %>% mutate(CpG = sum(gregexpr("CG", seq, fixed=TRUE)[[1]] > 0))
Run Code Online (Sandbox Code Playgroud)

我试图让 purrr::map 工作,但我失败了......这是我无法运行的尝试:

test %>% mutate(CpG = map(~sum(gregexpr("CG", seq, fixed=TRUE)[[1]] > 0)))
test %>% mutate(CpG = map(seq, ~sum(gregexpr("CG", .x, fixed=TRUE)[[1]] > 0)))
Run Code Online (Sandbox Code Playgroud)

编辑:时间基准

看起来stringi::stri_count_fixed是测试集上的最佳选择。

microbenchmark(
  mutate(test, CpG = stringr::str_count(seq, "CG")),
  mutate(test, CpG = purrr::map_int(seq, ~sum(gregexpr("CG", .x, fixed=TRUE)[[1]] > 0))),
  mutate(test, CpG = Biostrings::vcountPattern("CG", DNAStringSet(seq))),
  mutate(test, …
Run Code Online (Sandbox Code Playgroud)

regex r dplyr purrr

4
推荐指数
1
解决办法
1559
查看次数

在小标题的整行中搜索字符串?

我正在尝试清理来自许多不同组的样本信息表,因此我关心的治疗信息可能位于任意数量的不同列中。这是一个抽象的例子:

sample_info = tribble(
  ~id, ~could_be_here, ~or_here,    ~or_even_in_this_one,
  1,   NA,             "not_me",    "find_me_other_stuff",
  2,   "Extra_Find_Me", NA,         "diff_stuff",
  3,   NA,              "Find_me",  NA,
  4,   NA,              "not_here", "not_here_either"
)
Run Code Online (Sandbox Code Playgroud)

我想在哪里找到“find_me”1)不区分大小写,2)它可以在任何列中,3)它可以作为更大字符串的一部分。我想创建一列,判断是否在任何列中找到“find_me”,该列为 TRUE 或 FALSE。我怎样才能做到这一点?(我想过对unite所有列进行 ing,然后str_detect在混乱的情况下运行 a,但一定有一种不那么老套的方法,对吧?)

需要明确的是,我想要一个相当于 的最终小标题sample_info %>% mutate(find_me = c(TRUE, TRUE, TRUE, FALSE))

我希望在下面链接的类似情况下使用类似的东西stringr::str_detect(., regex('find_me', ignore_case = T))pmap_lgl(any(c(...) <insert logic check>))但我不确定如何将它们组合成一个兼容变异的语句。

我查看过的内容:
按行操作查看是否有任何列位于任何其他列表中

R:使用str_detect时如何忽略大小写?

在R中,检查字符串是否出现在数据帧的行中(在任何列中)

r stringr dplyr purrr tibble

4
推荐指数
1
解决办法
1030
查看次数

标签 统计

dplyr ×2

purrr ×2

r ×2

regex ×1

stringr ×1

tibble ×1