过滤向量上的数据框 [英] Filtering a data frame on a vector

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

问题描述

我有一个带有 ID 列的数据框 df,例如 AB 等.我还有一个包含某些 ID 的向量:

I have a data frame df with an ID column eg A,B,etc. I also have a vector containing certain IDs:

L <- c("A", "B", "E")

如何过滤数据框以仅获取向量中存在的 ID?个别地,我会使用

How can I filter the data frame to get only the IDs present in the vector? Individually, I would use

subset(df, ID == "A")

但是我如何过滤整个向量?

but how do I filter on a whole vector?

推荐答案

您可以使用 %in% 运算符:

You can use the %in% operator:

> df <- data.frame(id=c(LETTERS, LETTERS), x=1:52)
> L <- c("A","B","E")
> subset(df, id %in% L)
   id  x
1   A  1
2   B  2
5   E  5
27  A 27
28  B 28
31  E 31

如果您的 ID 是唯一的,您可以使用 match():

If your IDs are unique, you can use match():

> df <- data.frame(id=c(LETTERS), x=1:26)
> df[match(L, df$id), ]
  id x
1  A 1
2  B 2
5  E 5

或将它们设为数据框的行名并按行提取:

or make them the rownames of your dataframe and extract by row:

> rownames(df) <- df$id
> df[L, ]
  id x
A  A 1
B  B 2
E  E 5

最后,对于更高级的用户,如果速度是一个问题,我建议查看 data.table 包.

Finally, for more advanced users, and if speed is a concern, I'd recommend looking into the data.table package.

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

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