Last active
May 21, 2017 20:11
-
-
Save Torenable/647adf072f5b0886b5e4c409cb27874c to your computer and use it in GitHub Desktop.
Programming paradigm for by row mapper and by column mapper
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
data(iris) | |
# Apply a function to rows | |
row_sum = function(...) { | |
each_row = list(...) | |
# call by position | |
each_row[[1]] + # Sepal.Length | |
each_row[[2]] + # Sepal.Width | |
each_row[[3]] + # Petal.Length | |
each_row[[4]] # Petal.Width | |
# call by column name | |
each_row$Sepal.Length + | |
each_row$Sepal.Width + | |
each_row$Petal.Length + | |
each_row$Petal.Width | |
} | |
iris[c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")] %>% | |
pmap(row_sum) | |
# Apply a function to columns | |
col_function = function(x) { | |
x + 1 | |
} | |
iris[c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")] %>% | |
map(col_function) | |
## A better approach is to use `dplyr` | |
iris[c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")] %>% | |
mutate_each(funs(col_function)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment