Reputation: 3175
I guess this might be a rather simple question, but how to do this (base R):
df <- data.frame(x=10:1,y=(1:10)^2)
df[match(c(3,5,7), df$x),]
in idiomatic dplyr parlance:
tb <- dplyr::as.tbl(df)
dplyr::filter(tb, ??? )
or, in other words, what should go into ???
to make it functionally equivalent to the first snippet? Please note that the order of rows in resulting dataframe/tibble is relevant.
Upvotes: 1
Views: 1469
Reputation: 13570
Using filter
as well:
df %>%
filter( x %in% c(3, 5, 7)) %>%
group_by(x) %>%
slice(1)
Output:
x y
1 7 16
2 5 36
3 3 64
sqldf
package:
library(sqldf)
sqldf('SELECT *
FROM df
WHERE x IN (3, 5, 7)
GROUP BY x
LIMIT 3')
Upvotes: 1
Reputation: 3175
As suggested by @RichScriven: use dplyr::slice(df, match(c(3, 5, 7), x))
instead of dplyr::filter
.
Upvotes: 5