Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R set variable equal to what function returns. Re-evaluate variable again each time it is called [duplicate]

I'm not a developer, and I can't express well what I need in simple words. It is connected to things like environments, scoping, enclosure, and perhaps pointers and references.

It should be clear with code:

a<-c(1,2)
b<-length(a)
a<-c(1,2,3)
b
[1] 2

I want b to return 3.

What do I change in the second line? Is it possible to do it without defining new custom functions and using external packages?

Failed trying eval, assign, <<- so far

like image 989
stuckNlazy Avatar asked Jan 30 '15 00:01

stuckNlazy


1 Answers

I'm not recommending that you should actually use it, but makeActiveBinding() will do what you're asking for:

makeActiveBinding("b", function() length(a), .GlobalEnv)
a <- c(1,2)
b
# [1] 2
a <- c(1,2,4)
b
# [1] 3
like image 85
Josh O'Brien Avatar answered Oct 03 '22 21:10

Josh O'Brien