Skip to content

Instantly share code, notes, and snippets.

@kevinushey
Last active November 10, 2022 21:16
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinushey/7538142b5e16dd3b7200 to your computer and use it in GitHub Desktop.
Save kevinushey/7538142b5e16dd3b7200 to your computer and use it in GitHub Desktop.
A python-style enumerate function for R.
enumerate <- function(X, FUN, ...) {
result <- vector("list", length(X))
for (i in seq_along(result)) {
tmp <- FUN(X[[i]], i, ...)
if (is.null(tmp))
result[i] <- list(NULL)
else
result[[i]] <- tmp
}
result
}
l <- list(a = 1, b = 2, c = 3)
enumerate(l, function(x, i) {
cat("Name: ", names(l)[[i]], "\n")
cat("Value: ", x, "\n")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment