问题
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