Skip to content

Instantly share code, notes, and snippets.

@hschnegg
Last active December 15, 2015 21:09
Show Gist options
  • Save hschnegg/5323203 to your computer and use it in GitHub Desktop.
Save hschnegg/5323203 to your computer and use it in GitHub Desktop.
Higher Order Functions in R
# 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