Skip to content

Instantly share code, notes, and snippets.

@stephlocke
Last active August 29, 2015 14:14
Show Gist options
  • Save stephlocke/1749e0f9055947037ec2 to your computer and use it in GitHub Desktop.
Save stephlocke/1749e0f9055947037ec2 to your computer and use it in GitHub Desktop.
Exploring program flow with magrittr
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"]]
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)
## 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)
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