简体   繁体   中英

How to access function arguments (if function is passed as string) in R

warn <- NULL
withwarn <- function(fun) { tryCatch(fun, warning=function(w) { 
  warn <<- append(warn, paste(time, conditionMessage(w))) } )}

withwarn(reqHistoricalData(tws,x,time,'1 min','5 D','0','HISTORICAL_VOLATILITY'))

I pass a function to tryCatch and would like to have the value of argument time I tried several proposed ways with sys.call etc. but it seems that my problem is different: to function(w), time is not passed, and in function(fun) time is only part of the function string (only evaluated in tryCatch later on)

EDIT (Work-Around):

I just added another argument withwarn <- function(fun,y) for time .

How about this:

warn <- NULL
withwarn <- function(fun) { 
    args <- match.call()
    time_arg <- if("time" %in% names(args[[2]])) 
        eval(args[[2]][["time"]])
    else {
        eval(args[[2]][[4]])
    } 
    tryCatch(fun, warning=function(w) { warn <<- append(warn, paste(time_arg, conditionMessage(w))) } )
}

reqHistoricalData <- function(tws, x, time, ...) warning("some warning.")

ans <- withwarn(reqHistoricalData(tws, x, Sys.time(), '1 min','5 D','0','HISTORICAL_VOLATILITY'))

However, your workaround in your question looks better/cleaner to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM