【发布时间】:2016-01-03 06:51:40
【问题描述】:
我正在使用purrr 做一些工作,并希望有一个完整的管道解决方案来解决这个问题。我正在使用sapply,但认为这不是最佳解决方案。它适用于这个小演示,但在实际数据中,ch1 的长度 >50,000,ch2 的长度 >100。
library(stringr)
library(purrr)
ch1 <- c("something very interesting or perhaps it is not", "lions, tigers and elephants are safari animals", "once upon a time there was a big castle",
"I have not seen anything as a big as elephants")
ch2 <- c("big", "not")
对于ch2 的每个元素,我们想看看它们是否出现在ch1 的每个元素中。
str_detect(ch1, ch2[1]) # FALSE FALSE TRUE TRUE
str_detect(ch1, ch2[2]) # TRUE FALSE FALSE TRUE
尝试使用purrr 对所有ch1 应用函数:
ch1 %>% map_lgl(str_detect(., ch2[2])) # TRUE FALSE FALSE TRUE
我可以使用sapply 为整个ch2 执行此操作:
sapply(ch2, function(x) ch1 %>% map_lgl(str_detect(., x)))
big not
[1,] FALSE TRUE
[2,] FALSE FALSE
[3,] TRUE FALSE
[4,] TRUE TRUE
但是,对于真实的数据集,我认为必须有一个完整的purrr 解决方案——比如使用map2,即处理两个列表——但显然它不可能是那个特定的,因为它需要相同长度的列表.
【问题讨论】: