R subset a data frame with multiple keys [closed]

一个人想着一个人 提交于 2019-12-02 19:16:31

问题


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.


回答1:


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'))



回答2:


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


来源:https://stackoverflow.com/questions/14465996/r-subset-a-data-frame-with-multiple-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!