0

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
  • 1
    df[df$id %in% ids,]. Or subset(df,subset=id %in% ids) Commented Jul 23, 2015 at 4:00

1 Answer 1

2

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), ])
Sign up to request clarification or add additional context in comments.

2 Comments

Or library(data.table);setDT(df, key='id')[.(2:4)]
are you using the devel version? Otherwise you may need setkey(setDT, id)[.(2:4)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.