Last active
December 15, 2015 21:09
-
-
Save hschnegg/5323203 to your computer and use it in GitHub Desktop.
Higher Order Functions in 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
# Dummy attributes matrix | |
x <- matrix(c(1:12), ncol=4) | |
# Select attributes for combination (TRUE: in) | |
s1 <- c(TRUE, TRUE, FALSE, FALSE) | |
s2 <- c(FALSE, TRUE, FALSE, TRUE) | |
sel.x <- data.frame(s1, s2) | |
# Use higher order functions | |
# Use Map to calculate mean of attributes selected in s1 and s2 (returns list of vectors) | |
Map(function(p) {rowMeans(x[, p])}, sel.x) | |
# Reduce returned list using sum '+' (returns vector) | |
Reduce('+', (Map(function(p) {rowMeans(x[, p])}, sel.x))) | |
# Reduce previous list using funcion data.frame (returns data.frame!) | |
Reduce(data.frame, Map(function(p) {rowMeans(x[, p])}, sel.x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment