根据一行中的值在r中选择数据帧中的行 [英] Select rows in a dataframe in r based on values in one row

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

问题描述

我有一个玩具数据框。

a = rep(1:5, each=3)
b = rep(c("a","b","c"), each = 5)
df = data.frame(a,b)

   a b
1  1 a
2  1 a
3  1 a
4  2 a
5  2 a
6  2 b
7  3 b
8  3 b
9  3 b
10 4 b
11 4 c
12 4 c
13 5 c
14 5 c
15 5 c

我也有一个索引。

idx = c(2,3,5)

选择由idx指定的a为2,3或5的所有行。

I want to select all the rows where the a is either 2, 3, or 5 as specified by the idx.

我尝试过以下操作:但是没有一个工作。

I've tried the following; but none of them works.

df[df$a==idx, ]
subset(df, df$a==idx)

这不应该太难了。

推荐答案

使用%参数

Use the %in% argument

df[df$a %in% idx,] 

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

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