根据向量中的值过滤数据框行 [英] Filter data frame rows based on values in vector
问题描述
当要删除的值存储在向量中时,从数据框中过滤行的最佳方法是什么?就我而言,我有一列包含日期并想删除多个日期.
What is the best way to filter rows from data frame when the values to be deleted are stored in a vector? In my case I have a column with dates and want to remove several dates.
我知道如何删除对应于 one 天的行,使用 !=
,例如:
I know how to delete rows corresponding to one day, using !=
, e.g.:
m[m$date != "01/31/11", ]
要删除向量中指定的多个日期,我尝试了:
To remove several dates, specified in a vector, I tried:
m[m$date != c("01/31/11", "01/30/11"), ]
但是,这会生成一条警告消息:
However, this generates a warning message:
Warning message:
In `!=.default`(m$date, c("01/31/11", "01/30/11")) :
longer object length is not a multiple of shorter object length
Calls: [ ... [.data.frame -> Ops.dates -> NextMethod -> Ops.times -> NextMethod
基于多个值应用过滤器的正确方法是什么?
What is the correct way to apply a filter based on multiple values?
推荐答案
nzcoops 非常赞同他的建议.不久前我在 R Chat 中提出了这个问题,Paul Teetor 建议定义一个新函数:
nzcoops is spot on with his suggestion. I posed this question in the R Chat a while back and Paul Teetor suggested defining a new function:
`%notin%` <- function(x,y) !(x %in% y)
然后可以如下使用:
foo <- letters[1:6]
> foo[foo %notin% c("a", "c", "e")]
[1] "b" "d" "f"
不用说,这个小宝石现在在我的 R 个人资料中 并且经常使用.
Needless to say, this little gem is now in my R profile and gets used quite often.
这篇关于根据向量中的值过滤数据框行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!