Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Set function parameters within the global environment. Useful for debugging R functions.
#' Set function parameters for debugging.
#'
#' Sets the defauls for the parameters in the given function witin an environment.
#'
#' @param fun the function whose parameters should be set.
#' @param envir the environment to set those parameters.
#' @param missing.value value to assign to parameters that do not have a defautl value.
#' @param overwrite should parameters already defined be overwritten.
setFunctionParams <- function(fun,
envir=.GlobalEnv,
missing.value,
overwrite=FALSE) {
setValue <- function(name, value, missing.value=missing.value) {
if(nchar(name) > 0 & !missing(value)) {
if(!overwrite & exists(x=name, envir=envir)) {
message(paste0('Value for ', name, ' already defined in the environment'))
} else {
tryCatch( {
message(paste0('Setting ', name, ' = ', eval(value)))
assign(name, eval(value), envir)
}, error=function(e) {
warning(paste0('Cannot set value for ', name))
return(FALSE)
})
}
} else if(missing(value) & name != '...') {
if(!missing(missing.value)) {
message(paste0('No value defined for ', name,
'. Setting to ', missing.value))
assign(name, value, envir=envir)
} else {
message(paste0('No value defined for ', name, '.'))
}
}
return(TRUE)
}
fun.list <- as.list(fun)
revisit <- integer()
for(i in seq_along(fun.list)) {
name <- names(fun.list)[i]
value <- fun.list[[i]]
if(!setValue(name, value)) { revisit <- c(revisit, i) }
}
for(i in revisit) {
# We will try a second time in case an earlier parameter relies on the
# value of a later value. This may still not work all the time if there
# is a more complex interrelationship among the parameters.
name <- names(fun.list)[i]
value <- fun.list[[i]]
setValue(name, value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.