Created
January 5, 2017 10:05
-
-
Save bedantaguru/159fedbab79250da1b69ee5b9ef17eca to your computer and use it in GitHub Desktop.
Cool R Functions
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
get_current_function_call_hierarchy<- function(only_function_names = T){ | |
call_list <- sys.status()$sys.calls | |
call_list <- call_list[-length(call_list)] | |
call_list <- call_list[-length(call_list)] | |
if(length(call_list)==0){ | |
return(character(0)) | |
} | |
if(!only_function_names){ | |
return(as.character(call_list)) | |
} | |
return(call_list %>% lapply(as.character) %>% lapply("[[",1) %>% unlist()) | |
} |
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
f <- function(test = T){ | |
h<- function(){ | |
get_current_function_call_hierarchy() | |
} | |
j<-function(){ | |
h() | |
} | |
k<- function(){ | |
j() | |
} | |
if(test){ | |
h() | |
}else{ | |
k() | |
} | |
} |
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
f <- function(x){ | |
x+1+slow_inside() | |
} | |
x <- f | |
for(i in 1:5){ | |
print(x(1)) | |
x<-slow_me(x) | |
} | |
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
slow_me<- function(f){ | |
# making clone of the function otherwise same object will refer in following line | |
slow_function <- f | |
h <- function(...){ | |
slow_function(...) | |
} | |
return(h) | |
} | |
slow_inside <- function(){ | |
f_c_now <- g() | |
num <- table(f_c_now)["slow_function"] %>% as.numeric() | |
if(!is.na(num)){ | |
return(num) | |
}else{ | |
return(0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment