Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list of integer vectors in R

Tags:

r

Basic question: In R, how can I make a list and later populate it with vector elements?

l <- list()  l[1] <- c(1,2,3)  

This gives the error "number of items to replace is not a multiple of replacement length", so R is trying to unpack the vector. The only way I have found to work so far is to add the vectors when making the list.

l <- list(c(1,2,3), c(4,5,6)) 
like image 886
Tony Avatar asked Apr 27 '11 21:04

Tony


People also ask

How do I create a list vector in R?

list() function in R creates a list of the specified arguments. The vectors specified as arguments in this function may have different lengths. Syntax: list(arg1, arg2, ..)

How do I create an int list in R?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.

Is a list the same as a vector in R?

A list is actually still a vector in R, but it's not an atomic vector. We construct a list explicitly with list() but, like atomic vectors, most lists are created some other way in real life.


2 Answers

According to ?"[" (under the section "recursive (list-like) objects"):

 Indexing by ‘[’ is similar to atomic vectors and selects a list of  the specified element(s).   Both ‘[[’ and ‘$’ select a single element of the list.  The main  difference is that ‘$’ does not allow computed indices, whereas  ‘[[’ does.  ‘x$name’ is equivalent to ‘x[["name", exact =  FALSE]]’.  Also, the partial matching behavior of ‘[[’ can be  controlled using the ‘exact’ argument. 

Basically, for lists, [ selects more than one element, so the replacement must be a list (not a vector as in your example). Here's an example of how to use [ on lists:

l <- list(c(1,2,3), c(4,5,6)) l[1] <- list(1:2) l[1:2] <- list(1:3,4:5) 

If you only want to replace one element, use [[ instead.

l[[1]] <- 1:3 
like image 123
Joshua Ulrich Avatar answered Oct 08 '22 01:10

Joshua Ulrich


Use [[1]] as in

l[[1]] <- c(1,2,3) l[[2]] <- 1:4 

and so. Also recall that preallocation is much more efficient, so if you know how long your list is going to be, use something like

l <- vector(mode="list", length=N) 
like image 20
Dirk Eddelbuettel Avatar answered Oct 08 '22 00:10

Dirk Eddelbuettel