Created
August 21, 2020 23:18
-
-
Save MyKo101/f79c4beebb10d1805d994df64001f804 to your computer and use it in GitHub Desktop.
`subsetters` operators for `data.tables`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
`[[.data.table` <- function(data,subset){ | |
subset(data,eval(subset,data)) | |
} | |
subsetter <- function(x){ | |
new_subsetter(substitute(x)) | |
} | |
new_subsetter <- function(x){ | |
structure(x,class=c("subsetter","call")) | |
} | |
`%is%` <- function(lhs,rhs){ | |
lhs_nm <- deparse(substitute(lhs)) | |
rhs_2 <- substitute(rhs)[[2]] | |
rhs_structured <- new_subsetter(rhs_2) | |
assign(lhs_nm, | |
rhs_structured, | |
parent.frame()) | |
} | |
`&.subsetter` <- function(a,b){ | |
new_subsetter( | |
as.call(list(quote(`&`),a,b)) | |
) | |
} | |
`|.subsetter` <- function(a,b){ | |
new_subsetter( | |
as.call(list(quote(`|`),a,b)) | |
) | |
} | |
`!.subsetter` <- function(x){ | |
new_subsetter( | |
as.call(list(quote(`!`),x)) | |
) | |
} | |
print.subsetter <- function(x){ | |
cat("<unevaluated data.table subsetting operation>\n") | |
cat(">> ",format(x)) | |
} | |
flights14 <- fread("https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv") | |
JFK %is% (origin == "JFK") | |
WITHIN_6_MONTHS %is% (month == 6L) | |
TO_LAX %is% (dest == "LAX") | |
jfk_flights_all <- flights14[[JFK]] | |
jfk_flights <- flights14[[JFK & WITHIN_6_MONTHS]] | |
jfk_not_lax <- flights14[[JFK & !TO_LAX]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment