Home > Net >  Can R list refer its own objects?
Can R list refer its own objects?

Time:09-03

Is it possible for a list in R to refer its own objects, while defining it?

Example:

ui_names <- list(
  gen_button = 'Generate Report',
  gen_description = sprintf("Press '%s' button to generate validation report.", gen_button)
)

Code above throws error object 'gen_button' not found. If I change gen_button to ui_names$gen_button then it shows object 'ui_names' not found error, which totally makes sense since the list is not defined yet.

I know I could go:

ui_names <- list(gen_button = 'Generate Report')
ui_names$gen_description <- sprintf("Press '%s' button to generate validation report.", ui_names$gen_button)

but I was wondering if is it possible for a list to refer itself during definition?

CodePudding user response:

It is not possible with list(). However, there is a function tibble::lst() that allows to do that. If you have a problem with tidyverse dependencies, this function has also been adapted in the package poorman (which only relies on base R):

tibble::lst(
  gen_button = 'Generate Report',
  gen_description = sprintf("Press '%s' button to generate validation report.", gen_button)
)
#> $gen_button
#> [1] "Generate Report"
#> 
#> $gen_description
#> [1] "Press 'Generate Report' button to generate validation report."

poorman::lst(
  gen_button = 'Generate Report',
  gen_description = sprintf("Press '%s' button to generate validation report.", gen_button)
)
#> $gen_button
#> [1] "Generate Report"
#> 
#> $gen_description
#> [1] "Press 'Generate Report' button to generate validation report."

Created on 2022-09-02 by the reprex package (v2.0.1)

  • Related