Skip to content

Instantly share code, notes, and snippets.

@notoriousb1t
Last active June 8, 2016 19:29
Show Gist options
  • Select an option

  • Save notoriousb1t/ac2a834d37cf5737c0841244ff5b8a57 to your computer and use it in GitHub Desktop.

Select an option

Save notoriousb1t/ac2a834d37cf5737c0841244ff5b8a57 to your computer and use it in GitHub Desktop.
# 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);
@notoriousb1t

Copy link
Copy Markdown
Author

This example shows how to write a map, filter, and reduce function using the R language.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment