Skip to content

Instantly share code, notes, and snippets.

@slwu89
Last active July 29, 2017 00:47
Show Gist options
  • Save slwu89/bf91a976616681aca15b1d54de786b34 to your computer and use it in GitHub Desktop.
Save slwu89/bf91a976616681aca15b1d54de786b34 to your computer and use it in GitHub Desktop.
R tricks
# passArgsReplicate: how to pass additional named args as ... to function in replicate
passArgsReplicate <- function(n, func, ...){
args = as.list(substitute(list(...)))[-1L]
replicate(n = n,expr = do.call(func,args),simplify = FALSE)
}
# test calling and using global variables on different parallel processes
library(parallel)
parTest <- function(arg){
x <<- sample(x = 10,size = 1)
return(rnorm(n = x,mean = arg,sd = 1))
}
parOut = mclapply(1:10,parTest)
# what is an active binding and how do we use it?
# an active binding is like a standard variable but it will update its value every time it is accessed (ie; it is not static).
# in this example "getMyValue" will tell us how many rows are in "xx", note that if we change xx, so does the value "getMyValue" returns.
makeActiveBinding("getMyValue", function(){nrow(xx)}, .GlobalEnv)
xx = matrix(0,nrow = sample(100,1),ncol = 2)
getMyValue
# the versitality of the switch statement.
xx = function(x){
switch(x,
f = {return(rnorm(10))},
{print("not f")}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment