How to lazily define an element in a list based on a previous element?

Viewed 66

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 creates variables in 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)

1 Answers

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

Related