I'd like to set up a list with named entries whose values are left uninitialized (I plan to add stuff to them later). How do people generally do this? I've done:
mylist.names <- c("a", "b", "c") mylist <- as.list(rep(NA, length(mylist.names))) names(mylist) <- mylist.names
but this seems kind of hacky. There has to be a more standard way of doing this...right?
The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list.
To create an empty list in R, use the vector() function. The vector() function takes two arguments: mode and length. The mode is, in our case, is a list, and length is the number of elements in the list, and the list ends up actually empty, filled with NULL.
The list data structure in R allows the user to store homogeneous (of the same type) or heterogeneous (of different types) R objects. Therefore, a list can contain objects of any type including lists themselves.
I would do it like this:
mylist.names <- c("a", "b", "c") mylist <- vector("list", length(mylist.names)) names(mylist) <- mylist.names
A little bit shorter version than Thilo :)
mylist <- sapply(mylist.names,function(x) NULL)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With