r - R中使用dplyr基于单一条件过滤组

标签 r dataframe dplyr

我有两个数据框。 df1

    col1
 1  apples
 2 oranges
 3  apples
 4  banana

df2

   setID    col1
1      1  apples
2      1 oranges
3      1  apples
4      1  banana
5      2  apples
6      2  grapes
7      2 oranges
8      2  apples
9      3 oranges
10     3  grapes
11     3  banana
12     3  banana
13     4  apples
21     4  apples
31     4  banana
41     4 oranges

我使用 dplyr 包中的过滤器通过 df1$col1[1] 缩小 df2 的范围,并将结果放入 tempdf

> tempdf <- df2 %>% filter(df1$col1[1] == df2$col1)
> tempdf
  setID   col1
1     1 apples
2     1 apples
3     2 apples
4     2 apples
5     4 apples
6     4 apples

有没有办法可以看到与匹配的“苹果”具有相同 setID 的所有元素?像这样

         setID    col1
    1      1  apples
    2      1 oranges
    3      1  apples
    4      1  banana
    5      2  apples
    6      2  grapes
    7      2 oranges
    8      2  apples
    13     4  apples
    21     4  apples
    31     4  banana
    41     4 oranges

最佳答案

您可以在 filter 语句中使用 any 来过滤 df2$col1 的任何条目与第一个条目匹配的组df1$col1


数据:

df1 = read.table(text="col1
1  apples
2 oranges
3  apples
4  banana",header=T,stringsAsFactors=F)

df2 = read.table(text="   setID    col1
1      1  apples
2      1 oranges
3      1  apples
4      1  banana
5      2  apples
6      2  grapes
7      2 oranges
8      2  apples
9      3 oranges
10     3  grapes
11     3  banana
12     3  banana
13     4  apples
21     4  apples
31     4  banana
41     4 oranges",header=T,stringsAsFactors=F)

代码:

library(dplyr)
df2 %>% group_by(setID) %>% filter(any(col1==df1$col1[1]))

输出:

# A tibble: 12 x 2
# Groups:   setID [3]
   setID    col1
   <int>   <chr>
 1     1  apples
 2     1 oranges
 3     1  apples
 4     1  banana
 5     2  apples
 6     2  grapes
 7     2 oranges
 8     2  apples
 9     4  apples
10     4  apples
11     4  banana
12     4 oranges

希望这有帮助!

关于r - R中使用dplyr基于单一条件过滤组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48249217/

相关文章:

python - 如何在 SMALLINT 上使用 teradatasql 在数据库中插入空值,计算期间发生数字溢出

python - 列出列值在数据框中不唯一的行

r - purrr::map 相当于 dplyr::do

r - 在 R 中使用约束

r - data.table 未按两列正确汇总

Python - 根据表列中的逗号分隔值写入新行

R dplyr 使用自定义函数改变多列以创建新列

r - 无法在 dplyr 中使用多字变量,还是我遗漏了什么?

从 R 中单个列中的所有数据中删除前缀

r - 无法从 Rscript 批处理文件调用 roxygenize 函数