Application: reimplementing base::subset()
base::subset()
works like dplyr::filter()
: it selects rows of a data frame given an expression.
What do we need?
- Quote the expression to filter
- Figure out which rows in the data frame pass the filter
- Subset the data frame
subset2 <- function(data, rows) {
rows <- enquo(rows)
rows_val <- eval_tidy(rows, data)
stopifnot(is.logical(rows_val))
data[rows_val, , drop = FALSE]
}
sample_df <- data.frame(a = 1:5, b = 5:1, c = c(5, 3, 2, 4, 1))
# Shorthand for sample_df[sample_df$b == sample_df$c, ]
subset2(sample_df, b == c)
#> a b c
#> 1 1 5 5
#> 5 5 1 1