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

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

问题描述

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

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

I' m寻找类似以下代码的内容:

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),但由于盘与有效模式不匹配而无法正常工作(它只需要第一个元素。)

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).

有什么想法吗? thnx!

Any ideas? thnx!

推荐答案

我认为您正在寻找值匹配函数%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天全站免登陆