Last active
December 16, 2015 14:39
-
-
Save baptiste/5450365 to your computer and use it in GitHub Desktop.
Conversion between `my.function`, `my_function`, `myFunction` to find which variant actually exists in the R search path
This file contains hidden or 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
| split_dot <- function(x) | |
| strsplit(x, "\\.")[[1]] | |
| is_dot <- function(x) | |
| length(split_dot(x)) == 2L | |
| split_underscore <- function(x) | |
| strsplit(x, "_")[[1]] | |
| is_underscore <- function(x) | |
| length(split_underscore(x)) == 2L | |
| split_camel <- function(x){ | |
| strsplit(x, "[A-Z]")[[1]] | |
| } | |
| is_camel <- function(x) | |
| length(split_camel(x)) == 2L | |
| uncamel <- function(x){ | |
| sub("([A-Z])", "_\\L\\1", x, perl=TRUE) | |
| } | |
| camel <- function(x){ #function for camel case | |
| gsub('\\.(\\w?)', '\\U\\1', x, perl=T) | |
| } | |
| dot <- function(x){ | |
| gsub('_', '\\.', x, perl=T) | |
| } | |
| run_fun <- run.fun <- runFun <- function(fun){ | |
| fun_str <- deparse(substitute(fun)) | |
| ofun <- fun.str <- funStr <- fun_str | |
| # test the input type | |
| if(is_underscore(fun_str)){ | |
| fun.str <- dot(fun_str) | |
| funStr <- camel(fun.str) | |
| } | |
| if(is_camel(fun_str)){ | |
| funStr <- fun_str | |
| fun_str <- uncamel(funStr) | |
| fun.str <- dot(fun_str) | |
| } | |
| if(is_dot(fun_str)){ | |
| fun.str <- fun_str | |
| funStr <- camel(fun.str) | |
| fun_str <- uncamel(funStr) | |
| } | |
| if(fun_str == "run_fun") | |
| message("there's indeed no limit to the fun we can have") | |
| possibilities <- c(fun_str, funStr, fun.str) | |
| # message(possibilities) | |
| test <- FALSE | |
| for( testfun_str in possibilities){ | |
| test <- exists(testfun_str) && is.function(get(testfun_str)) | |
| if(test){ | |
| print(testfun_str) | |
| return(get(testfun_str)) | |
| } | |
| } | |
| message(ofun, " wasn't found, nor any of its variants") | |
| return(NULL) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment