Konrad
Konrad

Reputation: 18657

Create multiple lists from a string

I would like to create multiple lists from string. For example, when handling some data and charts I like to keep my workflow tidy and store objects within lists:

# For data
lstDta <- list()
# For charts
lstChrts <- list()

Creating more lists in the same manner looks boring and repetitive, which is not pleasant for the eye.

Problem

Ideally I would like to create the lists using a string with names:

mapply(assign, c("lstDta", "lstChrts"),
       rep(as.list(1),3), pos = 1)

Understandably, the code below returns error:

    > mapply(assign, c("lstDta", "lstChrts"),
+        rep(as.list(NULL),2), pos = 1)
Error in mapply(assign, c("lstDta", "lstChrts"), rep(as.list(NULL), 2),  : 
  zero-length inputs cannot be mixed with those of non-zero length

It would be possible to make it run, like that:

mapply(assign, c("lstDta", "lstChrts"),
       rep(as.list(1),2), pos = 1)

but the created object is numeric. What I would like to achieve boils down to: take this character vector and create an empty list for each value.

Upvotes: 0

Views: 563

Answers (1)

nrussell
nrussell

Reputation: 18612

Here's one way to do it:

sapply(c("lstDta", "lstChrts"), function(n) {
    assign(n, list(), envir = .GlobalEnv)
})

ls.str()
#lstChrts :  list()
#lstDta :  list()

Upvotes: 2

Related Questions