【问题标题】:Filter using multiple rows in two dataframes in R [duplicate]在R中使用两个数据帧中的多行进行过滤[重复]
【发布时间】:2018-10-30 05:37:39
【问题描述】:

数据

df1

  col1
1    a
2    a
3    b
4    e

df2

   col1  col2
1   1     a
2   1     c
3   1     c
4   1     e
5   2     a
6   2     b
7   2     b
8   2     e
9   3     a
10  3     a
11  3     b
12  3     e

我想使用 df1 过滤 df2。到目前为止,我有这个代码。

filter(df2, any(col2==df1$col1[1]))

这允许我逐行过滤。 但我想按多行过滤。一次不是整个 df1。我想使用 df1$col1[1:2] 过滤 df2。所以“a”后面跟着“a”。我尝试了以下代码,但收到了此消息。

filter(df2, col2==df1$col1[1] & col2==df1$col1[2])

[1] col1 col2 (或0-length row.names)

理想输出:

df2

   col1  col2
1   3     a
2   3     a
3   3     b
4   3     e

【问题讨论】:

    标签: r dataframe filter dplyr


    【解决方案1】:

    使用与@jaySf 的答案相同的方法,您也可以使用gregexpr

    matchpattern <- unlist(gregexpr(pattern = paste(df1$col1, collapse = ""), 
                                              paste(df2$col2, collapse = "")))
    df2[matchpattern:(matchpattern + nrow(df1) - 1),]
    
    #   col1 col2
    #9     3    a
    #10    3    a
    #11    3    b
    #12    3    e
    

    stri_locate 来自stringi

    library(stringi)
    index <- unlist(stri_locate(paste(df2$col2, collapse = ""), 
                                fixed = paste(df1$col1, collapse = "")))
    df2[index[1]:index[2],]
    
    #   col1 col2
    #9     3    a
    #10    3    a
    #11    3    b
    #12    3    e
    

    【讨论】:

      【解决方案2】:

      你可以使用包Biostrings

      df1 <- data.frame(col1=c("a", "a", "b", "e"))
      df2 <- data.frame(col1=c(rep(1, 4), rep(2, 4), rep(3, 4)),
                        col2=letters[c(1, 3, 3, 5, 1, 2, 2, 5, 1, 1, 2, 5)])
      
      aabe <- paste0(df1$col1, collapse = "")
      cand <- paste0(df2$col2, collapse = "")
      
      # # Install the package
      # source("https://bioconductor.org/biocLite.R")
      # biocLite("Biostrings")
      
      library(Biostrings)
      
      match <- matchPattern(aabe, cand)
      str(matchPattern(aabe, cand))
      
      x1 <- match@ranges@start
      x2 <- x1 + match@ranges@width - 1
      
      > df2[x1:x2, ]
         col1 col2
      9     3    a
      10    3    a
      11    3    b
      12    3    e
      

      【讨论】:

      • 酷。但我的要求之一是它不能一次匹配整个数据框。是否可以使用rollapply之类的东西?
      猜你喜欢
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 2012-03-07
      • 2019-09-30
      • 1970-01-01
      相关资源
      最近更新 更多