Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating variable value after redefinition

Tags:

r

A newbie question for you R folks:

Case scenario:

  1. I define variable A: A=number

  2. I define other variables based on A: B=number*A

  3. I change the definition of A: A=different number

[Q]. How can I get R to automatically update the value of B, without redefining it again?

E.g.: 1. A=1000; 2. B=A/10; (B=100) 3. Changed my mind: A=1100 after all;

>A
1100
>B
100

B should be 110 (1100/10), but its value has not been updated - hence it reads 100. Without redefining B, how can I update its value?

Thanks!

like image 626
Tony Avatar asked Jan 19 '23 17:01

Tony


2 Answers

Try this:

A <- 1000
makeActiveBinding("B", function() A/10, .GlobalEnv)
B
## [1] 100
A <- 1100
B
## [1] 110
like image 143
G. Grothendieck Avatar answered Feb 01 '23 01:02

G. Grothendieck


You are proposing making B a function of A (and possibly of the "number" in that second expression)

A=10
B <- function(Number=3.5) { A*Number }
B()
# [1] 35
A <- 15
B()
# [1] 52.5
like image 33
IRTFM Avatar answered Feb 01 '23 02:02

IRTFM