r - 在 R 中的两个数据框中使用多行过滤

标签 r dataframe filter dplyr

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





Matching a sequence in a larger vector

(2 个回答)


3年前关闭。




数据

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 rows> (or 0-length row.names)



理想输出:

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

最佳答案

您可以使用包 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

关于r - 在 R 中的两个数据框中使用多行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50434010/

相关文章:

r - 转换数据框并在 R 中对其进行汇总

r - dplyr:如何使用 mutate 函数制作一个结合前缀字符串和值序列的键

python - 从一个数据帧到另一个数据帧的查找值?

r - 放大 R 表达式中的单个符号 (/)

r - plot3d - 如何更改框颜色并删除轴刻度

python - Django 过滤查询解决方案

css - 如何在 png 图像上制作圆形阴影

python - 计算方差图像python

r - 使用 igraph 绘制网络

python - 如何在 pandas 交叉表上运行 join