Skip to content

Question on assignment

2 messages · Christofer Bogaso, Rui Barradas

#
Hello again, I was trying to understand how I can assign variables in
some other Environments which is different from that variable's
original Environment. Let say I have following nested functions:


fn <- function(x) {
		x1 <- function(y = x) {
				y1 <- log(y)
				y2 <- y^2
				return(0)
			}
		### I want the variable 'y1' is available here. WITHOUT using the
return() within x1()
		return(class(try(x1(), silent = TRUE)))
	}
fn(5)
fn("sd")


Here I want that the variable 'y1' which is defined within the
function x1() should be available in it's parent function fn() but not
in the Global Env. I have tried with the '<<-' operator, however could
not achieve what I want.

Can somebody point me towards the right direction?

Thanks for your help.
#
Hello,

Maybe using ?parent.frame. Something like


fn2 <- function(x) {
	x1 <- function(y = x) {
		env <- parent.frame()
		env$y1 <- log(y)
		y2 <- y^2
		return(0)
	}
	### I want the variable 'y1' is available here.
	### WITHOUT using the return() within x1()
	try(x1(), silent = TRUE)
	print(y1)  # available
	return(class(try(x1(), silent = TRUE)))
}

fn2(5)
fn2("sd")  # This will throw an error in print(y1)

The example needs to be refined but y1 is available to the parent.env of 
x1(), if x1() succeeds.


Hope this helps,

Rui Barradas

Em 16-03-2013 13:27, Christofer Bogaso escreveu: