I am vexed by the way R dynamically creates lists and I am hoping someone can help me understand what is going on and what to do to fix my code. My problem is that for assignments of a vector of length one, a named vector is assigned, but assignments of a vector of length greater than one, a list is assigned. My desired outcome is that a list is assigned no matter the length of the vector I am assigning. How do I achieve such a result?
For example,
types <- c("a", "b")
lst <- vector("list", length(types))
names(lst) <- types
str(lst)
List of 2
$ a: NULL
$ b: NULL
lst$a[["foo"]] <- "hi"
lst$b[["foo"]] <- c("hi", "SO")
str(lst)
List of 2
$ a: Named chr "hi"
..- attr(*, "names")= chr "foo"
$ b:List of 1
..$ foo: chr [1:2] "hi" "SO"
str(lst$a)
Named chr "hi"
- attr(*, "names")= chr "foo"
str(lst$b)
List of 1
$ foo: chr [1:2] "hi" "SO"
What I want to have as the outcome is a data structure that looks like this.
List of 2
$ a:List of 1
..$ foo: chr [1] "hi"
$ b:List of 1
..$ foo: chr [1:2] "hi" "SO"
While I also find it surprising, it is documented in
?[[:To override that behavior, you could specifically create empty lists before dynamically assigning to them:
or like Josh suggested below, replace your
lst <- vector("list", length(types))withlst <- replicate(length(types), list()).Now that
‘x’(lst$aorlst$b) is not‘NULL’but an empty list, your code should work as you expected: