-
-
Save vankesteren/2c1c7455e46209b72d478f397108abef to your computer and use it in GitHub Desktop.
Operator to perform an expression by group / conditionally on a factor / given a condition
This file contains hidden or 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
| `%|%` <- function(expr, group) { | |
| group <- as.factor(group) | |
| q <- rlang::enquo(expr) | |
| exx <- rlang::quo_get_expr(q) | |
| evv <- rlang::quo_get_env(q) | |
| glb <- codetools::findGlobals(as.function(list(exx))) | |
| gets <- lapply(glb, get, envir = evv) | |
| names(gets) <- glb | |
| recss <- function(o, ss) { | |
| # recursive subset | |
| if (inherits(o, "data.frame")) return(subset(o, ss)) | |
| if (is.vector(o) && length(o) == length(ss)) return(subset(o, ss)) | |
| if (is.list(o)) return(lapply(o, recss, ss = ss)) | |
| return(o) | |
| } | |
| v <- logical(length(group)) | |
| for (i in levels(group)) { | |
| subenv <- recss(gets, group == i) | |
| v[group == i] <- eval(exx, subenv) | |
| } | |
| return(v) | |
| } | |
| # example: outlier detection by group | |
| message(" %|% operator loaded. Usage:\n (abs(mtcars$mpg - mean(mtcars$mpg)) > var(mtcars$mpg)) %|% mtcars$cyl") |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
source("https://gist.githubusercontent.com/vankesteren/2c1c7455e46209b72d478f397108abef/raw/11d95982894f42dc925a9da7e73ff1eefa1b3a7c/by.R")