首页 文章

在R中使用两个数据帧中的多行进行过滤[重复]

提问于
浏览
4

这个问题在这里已有答案:

数据

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行>(或0长度row.names)

理想输出:

DF2

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

2 回答

  • 1

    你可以使用包 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
    
  • 3

    使用与@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
    

相关问题