Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variables in base R

Tags:

r

How to create please dependent variables in R ? For example

a <- 1
b <- a*2
a <- 2
b
# [1] 2

But I expect the result 4. How can R maintained relations automatically ? Thank you very much Explanation - I'm trying to create something as excel spreeadsheet with the relationships (formula or functions) between cells. Input for R is for examle csv (same values, some function or formula) and output only values

like image 946
user2408220 Avatar asked Dec 01 '22 15:12

user2408220


1 Answers

It sounds like you're looking for makeActiveBinding

a <- 1
makeActiveBinding('b', function() a * 2, .GlobalEnv)
b
# [1] 2
a <- 2
b
# [1] 4

The syntax is simpler if you want to use Hadley's nifty pryr package:

library(pryr)
b %<a-% (a * 2)

Most people don't expect variables to behave like this, however. So if you're writing code that others will be reading, I don't recommend using this feature of R. Explicitly update b when a changes or make b a function of a.

like image 72
Matthew Plourde Avatar answered Dec 15 '22 11:12

Matthew Plourde