Dynamic variables in the R base

How to create your own variables in R? for instance

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

But I expect result 4. How can R maintain relationships automatically? Thanks a lot Explanation. I am trying to create something like an excel spreeadsheet with relationships (formula or functions) between cells. The input for R is for csv example (same values, some functions or formulas) and only values ​​are displayed

+4
source share
4 answers

It looks like you are looking 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 the Hadley nifty package pryr:

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

, . , , , R. b, a b a.

+10

. , , , .

- , , . , , .

modified <- function(expr, value, ok, visible){
  if(exists("a")){
    assign("b", a*2, env = .GlobalEnv)
  }
  return(TRUE)
}

addTaskCallback(modified)

...

> a
Error: object 'a' not found
> b
Error: object 'b' not found
> a <- 2
> a
[1] 2
> b
[1] 4
> a <- 3
> a
[1] 3
> b
[1] 6

, , , , . R Excel, , Excel.

+6

R . . , , . , 20 b? ? ?

R .

.

sales = 100
costs = 90
profit = sales - costs

profit 10.

sales = 120

sales.

profit = sales - costs

profits 30.

, :

computeProfit = function(sales, costs){return(sales - costs)}

:

profit = computeProfit(sales, costs)

, .

+2
source

Although what you want to do is not entirely possible in R, with a simple modification bto the function and due to the lexical scope, you can actually have a "dependent variable" (view).

Define:

a <- 1

Define b as follows:

b <- function() {
    a*2
}

Then instead of using bto get the value of b, useb()

b() ##gives 2
a <- 4
b() ##gives 8
0
source

All Articles