2

There are 3 objects, v1, df1 and df2 as below:

v1  <- seq(1,5,by=1)
df1 <- tibble(a = v1, b = a * 10)
df2 <- tibble(x = df1$b*10)

df1 uses values of v1 and df2 uses column value of df1.

Now suppose the value of v1 gets changed:

v1 <- seq(10,50,by=10)

Whenever, v1 changes its value, how can the values of df1 and df2 be recomputed automatically and kept it in sync with v1?

Ajit Singh
  • 1,016
  • 13
  • 26

2 Answers2

2

This is not possible out of the box. You will have to write your own function doing so or use some external library, in R objects are a copy, so that means that df2is unaware of what v1 contains or how v1 changes after df2 is created. See also this similar question

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
DaveR
  • 1,696
  • 18
  • 24
1

A closure is something quite similar to what I think you are up to:

create_x <- function(x) {
  x_saved <- x

  get_df1 <- function() {
    tibble(a = x_saved, b = a * 10)
  }
  get_df2 <- function() {
    tibble(x = get_df1()$b * 10)
  }
  list(df1 = get_df1(), df2 = get_df2())
}

v1 <- create_x(seq(5))
v1$df1
v1$df2

v1 <- create_x(seq(5) * 10)
v1$df1 # access df1 and df2 without manual update
v1$df2
r.user.05apr
  • 5,356
  • 3
  • 22
  • 39