根据向量中的值从数据框中选择行 [英] Select rows from a data frame based on values in a vector

查看:179
本文介绍了根据向量中的值从数据框中选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的数据:

dt <- structure(list(fct = structure(c(1L, 2L, 3L, 4L, 3L, 4L, 1L, 2L, 3L, 1L, 2L, 3L, 2L, 3L, 4L), .Label = c("a", "b", "c", "d"), class = "factor"), X = c(2L, 4L, 3L, 2L, 5L, 4L, 7L, 2L, 9L, 1L, 4L, 2L, 5L, 4L, 2L)), .Names = c("fct", "X"), class = "data.frame", row.names = c(NA, -15L))

我想基于fct变量中的值从此数据框中选择行.例如,如果我希望选择包含"a"或"c"的行,则可以这样做:

I want to select rows from this data frame based on the values in the fct variable. For example, if I wish to select rows containing either "a" or "c" I can do this:

dt[dt$fct == 'a' | dt$fct == 'c', ]

产生

1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4

符合预期.但是我的实际数据更加复杂,我实际上想根据矢量中的值来选择行,例如

as expected. But my actual data is more complex and I actually want to select rows based on the values in a vector such as

vc <- c('a', 'c')

所以我尝试了

dt[dt$fct == vc, ]

但是那当然是行不通的.我知道我可以编写一些代码来遍历向量,然后拉出所需的行并将其附加到新的数据帧中,但是我希望有一种更优雅的方法.

but of course that doesn't work. I know I could code something to loop through the vector and pull out the rows needed and append them to a new dataframe, but I was hoping there was a more elegant way.

那么如何根据向量vc的内容过滤/子集我的数据?

So how can I filter/subset my data based on the contents of the vector vc?

推荐答案

看看?"%in%".

dt[dt$fct %in% vc,]
   fct X
1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4

您还可以使用?is.element:

dt[is.element(dt$fct, vc),]

这篇关于根据向量中的值从数据框中选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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