I have below function. I cannot alter the function in any way except the first block of code in the function.
In this simple example I want to display apply some function on returning object.
The point is the name of variable returned by function may vary and I'm not able to guess it.
Obviously I also cannot wrap the f
function into { x <- f(); myfun(x); x }
.
The below .Last.value
in my on.exit
call represents the value to be returned by f
function.
f <- function(param){
# the only code I know - start
on.exit(if("character" %in% class(.Last.value)) message(print(.Last.value)) else message(class(.Last.value)))
# the only code I know - end
# real processing of f()
a <- "aaa"
"somethiiiing"
if(param==1L) return(a)
b <- 5L
"somethiiiing"
if(param==2L) return(b)
"somethiiiing"
return(32)
}
f(1L)
# function
# [1] "aaa"
f(2L)
# aaa
# [1] 5
f(3L)
# integer
# [1] 32
Above code with .Last.value
seems to be working with lag (so in fact not working) and also the .Last.value
is probably not the way to go as I want to use the value few times like if(fun0(x)) fun1(x) else fun2(x)
, and because returned value might be a big object, copy it on the side is also bad approach.
Any way to use on.exit
or any other function which can help me to run my function on the f
function results without knowing result variable name?