Last active
August 29, 2015 14:14
-
-
Save stephlocke/1749e0f9055947037ec2 to your computer and use it in GitHub Desktop.
Exploring program flow with magrittr
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
library(data.table) | |
orig_subset<-function(workingdata){ | |
workingdata[["inputs"]][Species!='virginica'] | |
} | |
orig_mult<-function(workingdata){ | |
workingdata[["subset"]][,.SD*1.1,by=Species] | |
} | |
originalflow<-function(input){ | |
workingdata<-list() | |
workingdata[["inputs"]]<-data.table(input) | |
workingdata[["subset"]]<-orig_subset(workingdata) | |
workingdata[["multiply"]]<-orig_mult(workingdata) | |
return(workingdata) | |
} | |
# Either get everything for debug | |
oldresult<-originalflow(iris) | |
# or just get relevant bit | |
oldresult<-originalflow(iris)[["multiply"]] |
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
library(magrittr) | |
library(data.table) | |
get_subset<- . %>% data.table | |
multiply_values<- . %>% data.table | |
skeletonflow<-function(input){ | |
input %>% | |
data.table %>% | |
get_subset %>% | |
multiply_values | |
} | |
skeletonresult<-skeletonflow(iris) |
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
## You need to use a named input if you want to do conditions based on function values | |
library(magrittr) | |
library(data.table) | |
mytestfunction<-function(x,y = TRUE) { | |
x %>% | |
data.table %>% | |
{ | |
if(y) { | |
.[1:50] | |
} else { | |
.[1:75] | |
} | |
} %>% | |
nrow | |
} | |
mytestfunction(iris,0) |
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
library(magrittr) | |
library(data.table) | |
get_subset<- . %>% .[Species!='virginica'] | |
multiply_values<- . %>% .[,.SD*1.1,by=Species] | |
newflow<-function(input){ | |
input %>% | |
data.table %>% | |
get_subset %>% | |
multiply_values | |
} | |
newresult<-newflow(iris) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment