[R] sys.frame() and variables from parent frame
David Winsemius
dwinsemius at comcast.net
Wed Feb 27 01:20:39 CET 2013
On Feb 26, 2013, at 2:40 AM, José Miguel Delgado wrote:
> Dear R-help,
>
> I wrote the following lines in order to use a variable from a parent frame in my callM() function. I would like to solve this by only editing the callM(function). When I run this code I obtain a empty list, meaning that eval(ls(),sys.frame(-1)) could not access the variables in the parent function. Any suggestions? Thanks in advance!
>
> metaCall <- function()
> {
> NN <- 99
> callM()
> }
>
> callM <- function()
> {
> Ls <- eval(ls(),sys.frame(-1))
> print(Ls)
> ### use Ls to call a certain model named M
That doesn't make much sense.
> }
>
> metaCall()
>
I don't think you need the eval() call:
metaCall <- function()
{
NN <- 99
callM()
}
callM <- function()
{
Ls <- ls(env=sys.frame(-1))
cat(Ls)
}
metaCall()
NN
You should be aware that metaCall will not return anything since the last value is from the cat()-call or the print()-call and they each return NULL. If you wanted to go on from there and do something with 'NN", which is no longer a number but rather a character vector, you could, however.
Oh, I think I finally see .... the eval() was an attempt to retrieve the object named "NN"" in the parent.frame? That means you need :
?get
metaCall <- function()
{
NN <- 99
callM()
}
callM <- function()
{
Ls <- ls(env=sys.frame(-1))
str(get(Ls, env=sys.frame(-1)))
}
metaCall()
# num 99
--
David Winsemius
Alameda, CA, USA
More information about the R-help
mailing list