dplyr 过滤器:值包含在向量中 [英] dplyr filter : value is contained in a vector

查看:21
本文介绍了dplyr 过滤器:值包含在向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定特定向量的情况下,是否有使用 dplyr::filter 进行过滤的直接方法?

Is there a straight way to filter using dplyr::filter given an specific vector?

我正在寻找类似于以下代码的内容:

I'm looking for something like the code below:

top.food <- c('pizza', 'bacon', 'burger')

filter(orders, dish == 'pizza' | dish == 'bacon' | dish == 'burger')

我选择了一个字符向量,但它可以是任何类别.

我曾考虑使用 grepl 作为逻辑谓词 grepl(dish, top.food) 但它不起作用,因为dish 与有效模式不匹配(它只需要第一个元素).

I've thought about using grepl as a logical predicate grepl(dish, top.food) but it doesn't work since dish doesn't match a valid pattern (it takes just the 1st element).

有什么想法吗?谢谢!

推荐答案

我觉得你在找值匹配函数%in%.

I think you are looking for the value matching function %in%.

filter(orders, dish %in% top.food)

或者你可以切换到 slice() 并使用 match().

Or you can switch to slice() and use match().

slice(orders, match(dish, top.food, 0L))

我相信 slice()filter() 快一点,所以这可能对你有益.有关值匹配的所有详细信息,请参阅 help(match).

I believe that slice() is a bit faster than filter(), so that might be beneficial to you. See help(match) for all the details on value matching.

这篇关于dplyr 过滤器:值包含在向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆