[R] Question on assignment

Rui Barradas ruipbarradas at sapo.pt
Sat Mar 16 14:58:58 CET 2013


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:
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list