Created
January 24, 2019 21:46
-
-
Save coolbutuseless/fd1f0a3d4b38ee64223aee18192be6ce to your computer and use it in GitHub Desktop.
Python-ish list comprehensions in R [Proof of concept]
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
library(purrr) | |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
# Proof-of-concept | |
# Python style list comprehensions in R | |
# [ expression for item in list if conditional ] | |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
lc <- 'dummy' | |
class(lc) <- 'listcomprehension' | |
`[.listcomprehension` <- function(...) { | |
ll <- list(...)[-1] | |
if (length(ll) == 3L) { | |
map_dbl(keep(ll[[2]], ll[[3]]), ll[[1]]) | |
} else if (length(ll) == 2L) { | |
map_dbl(ll[[2]], ll[[1]]) | |
} else { | |
message("Not handled") | |
NULL | |
} | |
} | |
# [x + 1 for x in [1, 2, 3]] | |
lc[~.x + 1, c(1, 2, 3)] | |
# [x + 1 for x in [1, 2, 3] if x > 1] | |
lc[~.x + 1, c(1, 2, 3), ~.x > 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment