Dynamic variables in base R

后端 未结 4 1876
闹比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条回答
  •  独厮守ぢ
    2020-12-21 05:27

    Warning: This isn't a good idea and task callbacks really should only be used if you know what you're doing.

    You can do something like this but it's tedious and there are better ways to achieve your goal. You can make a function that will be called after every top level evaluation that basically does the reassignment for you.

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

    After running that you should be able to get this...

    > 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
    

    Note that if you want to emulate a spreadsheet it would probably just be better to define a function to take your input and do all the necessary calculations to get your desired output. R isn't Excel and it would be best if you don't treat it like Excel.

提交回复
热议问题