Last active
June 8, 2016 19:29
-
-
Save notoriousb1t/ac2a834d37cf5737c0841244ff5b8a57 to your computer and use it in GitHub Desktop.
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
| # define mapper function | |
| map <- function(list, fn) { | |
| i <- 0; | |
| len <- length(list); | |
| result <- vector(length = len); | |
| while (i < len) { | |
| i <- i + 1; | |
| result[i] <- fn(list[i]); | |
| } | |
| return(result); | |
| }; | |
| # define filter function | |
| filter <- function(list, fn) { | |
| i <- 0; | |
| len <- length(list); | |
| result <- vector(); | |
| while (i < len) { | |
| i <- i + 1; | |
| item <- list[i]; | |
| if (fn(item)) { | |
| result <- append(result, item); | |
| } | |
| } | |
| return(result); | |
| } | |
| # define reduce function | |
| reduce <- function(list, reducer, initial) { | |
| i <- 0; | |
| len <- length(list); | |
| current <- initial; | |
| while (i < len) { | |
| i <- i + 1; | |
| current <- reducer(current, list[i]); | |
| } | |
| return(current); | |
| }; | |
| # define dataset | |
| data <- c(1, 2, 3); | |
| # filter out even numbers: c(1, 3) | |
| data <- filter(data, function(n) { | |
| return(n %% 2 != 0); | |
| }) | |
| # map numbers to the power of 2: c(1, 9) | |
| data <- map(data, function(n) { | |
| return(n ** 2); | |
| }); | |
| # sum list of numbers. equivelant to sum(data): 10 | |
| data <- reduce(data, function(c, n) { | |
| return(c + n) + 1; | |
| }, 0); | |
| # print the number 10 | |
| print(data); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example shows how to write a map, filter, and reduce function using the R language.