Genrikh Lukianchuk Genrikh Lukianchuk - 1 month ago 7
R Question

How to make static variable dynamic?

Assume a simple code:

> sample(2,5,replace=TRUE)
[1] 2 1 1 1 2


When it is called again it can take other variables:

> sample(2,5,replace=TRUE)
[1] 1 2 2 1 2


However, when assigned to a variable it sticks to one predefined set:

> n <- (sample(2,5,replace=TRUE))
> n
[1] 1 1 2 1 1
> n
[1] 1 1 2 1 1
> n
[1] 1 1 2 1 1


How do we make n variable change its values then?

Answer

I'm side-stepping some issues of why you'd want to do this, but here's one way that's somewhat....advanced:

makeActiveBinding("n",function() sample(2,5,replace = TRUE),.GlobalEnv)
> n
[1] 2 2 1 2 1
> n
[1] 1 2 2 2 2
> n
[1] 2 1 1 1 1

What's happening here is that n is being created in the global environment and then linked to the function, so that whenever a value for n is needed it calls the function.

Comments