Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 <<-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading