Last active
June 14, 2024 10:13
-
-
Save kevinushey/7538142b5e16dd3b7200 to your computer and use it in GitHub Desktop.
A python-style enumerate function for R.
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
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