【问题标题】:Apply function over 2 character vectors return list - purrr在 2 个字符向量返回列表上应用函数 - purrr
【发布时间】: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,即处理两个列表——但显然它不可能是那个特定的,因为它需要相同长度的列表.

【问题讨论】:

    标签: r string sapply


    【解决方案1】:

    以下内容在大型数据集上可能会比您帖子中的代码快一点,它返回一个向量列表。

    library(stringr)
    library(purrr
    lst <- ch2 %>% split(ch2) %>% 
      map( ~ str_detect(ch1, .x))
    

    要返回一个矩阵,您可以使用以下内容:

    mat <- ch2 %>% split(ch2) %>% 
          map( ~ str_detect(ch1, .x)) %>%
          map_call(cbind)
    

    但是,由于map_call 只是do.call 的一个薄包装,它可能会有点慢。如果您可以使用 dplyr 并使用 data.frame 作为结果,则以下可能会快一点:

    library(dplyr)
    df <- ch2 %>% split(ch2) %>% 
          map( ~ str_detect(ch1, .x)) %>%
          as_data_frame() 
    

    已添加

    以下是使用map2 生成具有命名列的矩阵的解决方案

    # solution using map2
    mat2 <- ch1 %>% list %>%
            map2(ch2,  ~ str_detect(.x, .y)) %>%
            map_call(cbind)
    colnames(mat2) <- ch2
    

    也许最直接的生成带有列名的矩阵是:

    names(ch2) <- ch2
    mat3 <- ch2 %>% map( ~ str_detect(ch1, .x)) %>% 
            map_call(cbind)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多