Home > Back-end >  How to lazily define an element in a list based on the value of an previous value?
How to lazily define an element in a list based on the value of an previous value?

Time:02-11

Essentially, what I'm trying to achieve is similar to the functionality that exists for function arguments -

xx <- function(x, y = 2 * x){message('y is ', y)} # y is defined even when only the value of 'x' is supplied
xx(2) # Outputs "y is 4"

Similar to how y is lazily defined in the above, can I do something like this -

l <- list(x = 2, y = 2 * x) # This returns "Error: object 'x' not found" which I understand

I have tried a kludgy workaround involving l <- list(x <<- 2, y = 2 * x) which works but pollutes the global environment. So, I'm not too keen on using <<-

This is very similar to Using list elements in its' definition, but I'm interested in an r-base solution that involves defining the least amount variables in the global environment (including functions)

CodePudding user response:

for base R, You could use within:

l <- within(list(x = 2), {y = x*2; z =y 3})

in tidyverse, use the dplyr::lst or tibble::lst

  •  Tags:  
  • r
  • Related