[R] Dynamic Creation and Use of Object Names

Dr Eberhard Lisse no@p@m @end|ng |rom ||@@e@NA
Mon Aug 23 13:51:09 CEST 2021

Thank you,

more to study :-)-O


On 23/08/2021 10:20, Ivan Krylov wrote:
> On Mon, 23 Aug 2021 08:37:54 +0200
> Dr Eberhard Lisse <nospam using lisse.NA> wrote:
>> create the variables dynamically and add them to to
>> the grid (dynamically, ie adding more countries)
> In my opinion, creating variables in the global environment
> programmatically may lead to code that is hard to understand and debug
> [*]. A key-value data structure (a named list or a separate
> environment) would avoid the potential problems from variable name
> collision. How about the following:
> 1. Put the countries in a vector: c('Namibia', 'Germany', ...)
> 2. Use lapply() to get a list of objects returned from your PICTURE
>     function
> 3. To save the pictures into individual files, loop over the list. You
>     can use setNames on the step 1 or 2 to make it a named list and keep
>     the country names together with their pictures:
>     for (n in names(pictures)) {
>       dev.new()
>       print(pictures[[n]])
>       ggsave(paste0(n, '.png'), ...)
>       dev.off()
>     }
>     (You can also use the png() device and plot straight to the file,
>     avoiding the need to draw the plot in the window for a fraction of a
>     second and for ggsave().)
> 4. Use the grobs= argument of grid.arrange() to pass the list of
>     objects to arrange instead of passing individual objects via ...

To email me replace 'nospam' with 'el'

More information about the R-help mailing list