【问题标题】:Find rows where one column string is in another column using dplyr in R使用 R 中的 dplyr 查找一个列字符串在另一列中的行
【发布时间】:2017-10-08 01:04:49
【问题描述】:

希望拉回其中一列中的值作为字符串存在于另一列(在同一行内)的行。

我有一个 df:

A <- c("cat", "dog", "boy")
B <- c("cat in the cradle", "meet the parents", "boy mmets world")

df <- as.data.frame(A, B)

A       B
cat     cat in the cradle
dog     meet the parents
boy     boy meets world

我正在尝试这样的事情:

df2 <- df %>%
          filter(grepl(A, B)) # doesn't work because it thinks A is the whole column vector

df2 <- df %>%
          filter(B %in% A) # which doesn't work because it has to be exact

我希望它产生

A       B
cat     cat in the cradle
boy     boy meets world

提前致谢!

马特

【问题讨论】:

    标签: r regex dplyr grepl


    【解决方案1】:

    您可以使用 Map 将函数应用于两个向量,也可以使用 sapply 遍历行

    df %>%
      filter(unlist(Map(function(x, y) grepl(x, y), A, B)))
        A                 B
    1 cat cat in the cradle
    2 boy   boy mmets world
    
    df %>%
      filter(sapply(1:nrow(.), function(i) grepl(A[i], B[i])))
        A                 B
    1 cat cat in the cradle
    2 boy   boy mmets world
    

    【讨论】:

      【解决方案2】:

      我们可以通过Map 做到这一点

      df[mapply(grepl, df$A, df$B),]
      #    A                 B
      #1 cat cat in the cradle
      #3 boy   boy mmets world
      

      更新

      使用tidyverse,类似的选项是purrr::map2stringr::str_detect

      library(tidyverse)
      df %>% 
         filter(map2_lgl(B, A,  str_detect))
      #     A                 B
      #1 cat cat in the cradle
      #2 boy   boy mmets world
      

      数据

      df <- data.frame(A, B, stringsAsFactors=FALSE)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-16
        • 1970-01-01
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        • 2018-12-02
        相关资源
        最近更新 更多