Created
November 29, 2015 20:48
-
-
Save wjhopper/ac18d93c5390b936815f to your computer and use it in GitHub Desktop.
Observe the amazing obscurity of 100% "functional" R code!
This file contains 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
## Some sort of list comprehension using only functional programming | |
## techniques that returns a list holding the coefficients of variation | |
## (i.e. the mean divided by the standard deviation) for each column in the | |
## mtcars data set. | |
## This isn't the clearest code (i.e. its really hard to tell its dividing | |
## the mean by the standard deviation) but it uses absolutely no imperative control | |
## flow structures and no vectorized R functions, so if you can read and understand | |
## this you can do you some functional programming for great good =). I can't believe I | |
## actually figured this out, much less that I figured it out in like 5 minutes, | |
## so I decided to preserve it for posteriry in a gist. yay posterity! | |
a <- lapply(mtcars, | |
function(col) { | |
Reduce(`/`, lapply(list(mean,sd), | |
function(f) { | |
f(col,na.rm=TRUE) | |
})) | |
}) | |
## You can even write a function to do this for any data frame/list! | |
coef_of_var <- function(list_struct = mtcars, na.rm=TRUE) { | |
valid_cols <- vapply(list_struct, function(v) is.numeric(v) || is.logical(v), | |
logical(1)) | |
a <- lapply(list_struct[valid_cols], | |
function(col) { | |
Reduce(`/`, lapply(list(mean,sd), | |
function(f) { | |
f(col,na.rm=na.rm) | |
})) | |
}) | |
return(a) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment