Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare list object with M elements

Tags:

r

I want to declare a list containing M 3 by 3 matrices. If I knew the number M in advance, then I can declare such list by:

elm <- matrix(NA,3,3) ## Say M = 7 myList <- list(elm,elm,elm,elm,elm,elm,elm)  

This method becomes cumbersome if M is large. What's worse this method does not work if I do not know the value of M in advance. If I want to declare a vector of length M, I can do it by calling:

myVec <- rep(NA,M) 

even if I do not know the value of M in advance. Is there similar way to declare a list of size M?

like image 303
FairyOnIce Avatar asked Oct 12 '13 23:10

FairyOnIce


People also ask

How do I create a list of objects in R?

How to create a list in R programming? List can be created using the list() function. Here, we create a list x , of three components with data types double , logical and integer vector respectively. Its structure can be examined with the str() function.

How do I make a list of specific size in Python?

We can initialize a list of size n using a range() statement. The difference between using a range() statement and the None method is that a range() statement will create a list of values between two numbers. By default, range() creates a list from 0 to a particular value.

How do I create a list length in n in R?

To create an empty list of specific length in R programming, call vector(mode, length) function and pass the value of “list” for mode, and an integer for length. The default values of the items in the list would be NULL.

What is a list object in R?

A list is an object in R Language which consists of heterogeneous elements. A list can even contain matrices, data frames, or functions as its elements. 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.


2 Answers

Maybe this:

myls <- vector("list", length = S)

like image 181
alexis_laz Avatar answered Sep 20 '22 09:09

alexis_laz


Try

mylist <- rep(list(elm),7) 

which, for S=3, gives

[[1]]      [,1] [,2] [,3] [1,]   NA   NA   NA [2,]   NA   NA   NA [3,]   NA   NA   NA  [[2]]      [,1] [,2] [,3] [1,]   NA   NA   NA [2,]   NA   NA   NA [3,]   NA   NA   NA  [[3]]      [,1] [,2] [,3] [1,]   NA   NA   NA [2,]   NA   NA   NA [3,]   NA   NA   NA 

By the way, identical(matrix(NA,3,3),matrix(,3,3)) is true, since matrices are initialized to NA by default. See ?matrix.

like image 25
Frank Avatar answered Sep 22 '22 09:09

Frank