Skip to content

Instantly share code, notes, and snippets.

@dmi3kno
Created October 16, 2017 22:48
Show Gist options
  • Save dmi3kno/3c8851ec9eeba6792c28b0cf105f7fb2 to your computer and use it in GitHub Desktop.
Save dmi3kno/3c8851ec9eeba6792c28b0cf105f7fb2 to your computer and use it in GitHub Desktop.
Implementing column name proxy for custom tibble class
library(dplyr)
library(rlang)
library(purrr)
x <- tibble(year=2011:2015,
value=runif(5))
# extending the tibble class
class(x) <- unique(c("tbl_cf", class(x)))
attr(x, ".index") <- "year"
filter.tbl_cf<-function(x, ...){
# capture the args and substitute the .index
args_list <- quos(...) %>%
map(quo_name) %>%
map(~gsub(".index", attr(x, ".index"), .x)) %>%
map(~parse_quosure(.x))
# strip the class to avoid infinite loop
class(x) <- class(x)[-1]
res <- x %>%
dplyr::filter(UQS(args_list))
# restore the custom class
res(x) <- unique(c("tbl_cf", class(x)))
}
filter(x, .index == 2015)
@dmi3kno
Copy link
Author

dmi3kno commented Oct 16, 2017

The idea is that user does not have to care what the key property of the object is called. So long that the class is maintained, methods should be able to interpret reference to feature class attribute.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment