Home > database >  Create multiple null containers in R (to be used in "for loop"), using a simple code
Create multiple null containers in R (to be used in "for loop"), using a simple code

Time:02-14

I'm creating empty null containers, to collect values from a "for loop". Here is an example in my code, for which I've created 6 empty containers.

cont_min  <- NULL
cont_max  <- NULL
cont_unused <-  NULL
cont_n_rec  <- NULL
cont_n_don  <- NULL
cont_loop_time <- NULL

I need to create quite a few of these and it's using a lot of space using a line of code for each. Is there a way to create multiple containers without having a separate line of code? Many thanks

CodePudding user response:

You could use something like this:

names <- c('min', 'max', 'unused', 'n_rec', 'n_don', 'loop_time')
var_lst <- sapply(paste0('cont_', names), function(x) assign(x, NULL))
list2env(var_lst, .GlobalEnv)

CodePudding user response:

If we want to do this in a single line, an option is %<-% from zeallot

library(zeallot)
 c(cont_min, cont_max, cont_unused, cont_n_rec, cont_n_don, cont_loop_time) %<-% 
    rep(list(NULL), 6)

-checking

> cont_min
NULL
  •  Tags:  
  • r
  • Related