R subset a data frame with multiple keys [closed]

2019-03-06 08:52发布

I have the following data frame

id val
a  1
a  2
a  3
b  4
b  5
c  6

I would like to find a subset of this data frame using a subset of the id's. I know I can do the following if the subset criteria is just 1 value for e.g.

y = subset(x,id=='a')

However how do I get a subset if I have a set of several ids. For example c('a','b'). Doing

y = subset(x,id==c('a','b'))

does not give me what I want.

标签: r subset
2条回答
淡お忘
2楼-- · 2019-03-06 09:07

Try the %in% operator.

> id<-c("a","a","a","b","b","c")
> val<-c(1,2,3,4,5,6)
> x<-data.frame(cbind(id,val))
> subset(x,id %in%c('a','b'))
  id val
1  a   1
2  a   2
3  a   3
4  b   4
5  b   5
查看更多
贪生不怕死
3楼-- · 2019-03-06 09:16

You can subset with logical operators, e.g.

y=subset(x,id=='a' | id=='b')

or you can use the %in% operator:

y=subset(x,id %in% c('a','b'))
查看更多
登录 后发表回答