Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list with names but no entries in R/Splus?

Tags:

r

s-plus

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?

like image 700
lowndrul Avatar asked Apr 16 '11 16:04

lowndrul


People also ask

How do I create a named list in R?

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.

How do I name an empty list in R?

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.

Can a list contain a list in R?

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.


2 Answers

I would do it like this:

mylist.names <- c("a", "b", "c") mylist <- vector("list", length(mylist.names)) names(mylist) <- mylist.names 
like image 148
Thilo Avatar answered Sep 22 '22 10:09

Thilo


A little bit shorter version than Thilo :)

mylist <- sapply(mylist.names,function(x) NULL) 
like image 20
Wojciech Sobala Avatar answered Sep 21 '22 10:09

Wojciech Sobala