0
votes

Have a data.frame, df as below

id | name | value
1  | team1 | 3
1  | team2 | 1
2  | team1 | 1
2  | team2 | 4
3  | team1 | 0
3  | team2 | 6 
4  | team1 | 1
4  | team2 | 2 
5  | team1 | 3
5  | team2 | 0 

How do we subset the data frame to get rows for all values of id from 2:4 ?

We can apply conditionally like df[,df$id >= 2 & df$id <= 4] . But is there a way to directly use a vector of integer ranges like ids <- c(2:4) to subset a dataframe ?

One way to do this is df[,df$id >= min(ids) & df$id <= max(ids)].

Is there a more elegant R way of doing this ?

1
df[df$id %in% ids,]. Or subset(df,subset=id %in% ids) - Jason

1 Answers

2
votes

The most typical way is mentioned already, but also variations using match

with(df, df[match(id, 2:4, F) > 0, ])

or, similar

with(df, df[is.element(id, 2:4), ])