Skip to content

Instantly share code, notes, and snippets.

@coolbutuseless
Created January 24, 2019 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolbutuseless/fd1f0a3d4b38ee64223aee18192be6ce to your computer and use it in GitHub Desktop.
Save coolbutuseless/fd1f0a3d4b38ee64223aee18192be6ce to your computer and use it in GitHub Desktop.
Python-ish list comprehensions in R [Proof of concept]
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