Dynamic variables in base R

后端 未结 4 1877
闹比i
闹比i 2020-12-21 05:12

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

4条回答
  •  旧时难觅i
    2020-12-21 05:40

    Although what you want to do is not completely possible in R, with a simple modification of b into a function and thanks to lexical scoping, you actually can have a "dependent variable" (sort of).

    Define a:

    a <- 1
    

    Define b like this:

    b <- function() {
        a*2
    }
    

    Then, instead of using b to get the value of b, use b()

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

提交回复
热议问题