Reputation: 199
I am running a script with a predefined function that calculates a couple of by products before giving me the desired end result. Now I wanted to 'grep' some of these by products as I need them for further calculation.
I thought the normal way to do that is to call an element(say, t) within function f as f$t. However, in case I do get the error object of type closure is not subsetable. Is there some way to stillextract out of the function?
Thanks
Upvotes: 0
Views: 66
Reputation: 315
there is a better way to output the local variables of a function into the global environment. R provides a special assignment operator which comes in handy here.
myfunct <- function(x, y) {
val1 <<- x + y
val2 <<- x - y
result <- val1 * val2
return(result)
}
please notice the extra character in the assignment operator. what this does is that the variables val1 and val2 are assigned in the global environment and at the same time you can use it to calculate the result. you just return the result from the function. you can go ahead and play around with val1 and val2 in the global environment.
Edit after few comments : I agree that in general this will not be a good feature. but you have to understand the requirements of the question. my understanding was that there is a pre-written function which is being used which already has a form. now in such a case a lot of times you would want to debug the function without wanting to change the form of the function.
so without touching what the function is returning, if you want to output an internal variable, then this feature of R comes in very handy. but i agree, before you close R for the day, make sure you have removed all instances of this operator.
Upvotes: 0
Reputation: 51680
You cannot access local variables in the function, but you can return them as needed.
For instance if you have:
myfunct <- function(x, y)
{
val1 <- x + y
val2 <- x - y
result <- val1 * val2
return(result)
}
The only thing you have access to is the final result.
If you want to have access to val1
and val2
you can do:
myfunct <- function(x, y)
{
val1 <- x + y
val2 <- x - y
result <- val1 * val2
return(list(res=result, valsum=val1, valdiff=val2))
}
You can now do:
test <- myfunct(10, 20)
print(test$valsum)
print(test$valdiff)
print(test$res)
Upvotes: 1