Initialize a list of matrices in R
Also try this wrapper of *apply:
replicate(10, diag(2), simplify=F)
How to create a list of matrix in R
Try
x <- matrix(1:10, ncol=2)
y <- x+300
MATS <- list(x, y) # use 'list' instead of 'c' to create a list of matrices
MATS
[[1]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[2]]
[,1] [,2]
[1,] 301 306
[2,] 302 307
[3,] 303 308
[4,] 304 309
[5,] 305 310
Here you have to refer to MATS[[1]]
as if it were x
If you want to append a new matrix to the exiting list try
z <- x+500
MATS[[3]] <- z # appeding a new matrix to the existing list
MATS
[[1]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[2]]
[,1] [,2]
[1,] 301 306
[2,] 302 307
[3,] 303 308
[4,] 304 309
[5,] 305 310
[[3]]
[,1] [,2]
[1,] 501 506
[2,] 502 507
[3,] 503 508
[4,] 504 509
[5,] 505 510
One drawback of this approach is that you have to know the position in the list where you have to append the new matrix, if you don't know it or simply if you dont want this approach, then here's a trick:
unlist(list(MATS, list(z)), recursive=FALSE) # will give u the same list :D
R create list of matrices
You can use relist
to make the structure of x
similar to my_list
:
relist(x, my_list)
#[[1]]
#[[1]][[1]]
# [,1] [,2] [,3]
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 3 6 9
#[[1]][[2]]
# [,1] [,2] [,3]
#[1,] 2 8 14
#[2,] 4 10 16
#[3,] 6 12 18
#[[2]]
#[[2]][[1]]
# [,1] [,2] [,3]
#[1,] 3 12 21
#[2,] 6 15 24
#[3,] 9 18 27
#[[3]]
#[[3]][[1]]
# [,1] [,2] [,3]
#[1,] 4 16 28
#[2,] 8 20 32
#[3,] 12 24 36
Similar output is obtained using lapply
:
lapply(my_list, function(i) x[i])
If you want to avoid the nested output for single matrix and want it exactly as shown you can use :
lapply(my_list, function(i) if(length(i) > 1) x[i] else x[[i]])
#[[1]]
#[[1]][[1]]
# [,1] [,2] [,3]
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 3 6 9
#[[1]][[2]]
# [,1] [,2] [,3]
#[1,] 2 8 14
#[2,] 4 10 16
#[3,] 6 12 18
#[[2]]
# [,1] [,2] [,3]
#[1,] 3 12 21
#[2,] 6 15 24
#[3,] 9 18 27
#[[3]]
# [,1] [,2] [,3]
#[1,] 4 16 28
#[2,] 8 20 32
#[3,] 12 24 36
You can read the difference between [
and [[
here : The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe
Creating list of matrices in R
This could be helpful:
fact.cov <- list()
for (k in 15:fact.weight) {
fact.cov[[k]] <- var(fact.wealth.return[(k-1):k,])
};rm(k)
However, you should provide more details in order for your code to be reproduceable (e.g. what is fact.wealth.return
or fact.weight
).
creating a list of matrices in R
I would go about this by adding each matrix to a list at the time you actually create each matrix, e.g.
lst <- list(X_1, X_2, ..., X_N)
Then, when you want to apply a function to each matrix you can simply use lapply
, e.g.
result <- lapply(lst, function(x) fun(x))
where fun()
takes a matrix as input and does something with it.
R: initialize m by n matrices in an empty list
We can create a 3D array by specifying the dimensions
array(NA, c(2, 5, 10))
Or if we need a list
of matrices
lapply(1:10, matrix, data= NA, nrow=2, ncol=5)
a loop to create a list of matrices generated from two different data frames in R
The Mean.list
should be initialized outside the loop and it can be a NULL list
of length k
Mean.list <- vector('list', k)
for(i in 1:k){
df1.mean.vec <- colMeans(subset(df1, clster == i))
df2.mean.vec <- colMeans(subset(df2, clster == i))
Mean.mat <- as.matrix(rbind(df1.mean.vec, df2.mean.vec), row.names= FALSE)
Mean.list[[i]] <- Mean.mat
rm(Mean.mat)
gc()
names(Mean.list)[i] <- i
}
How to create a matrix of lists in R?
This builds that matrix although the print method does not display it in the manner you imagined:
matrix( list(c(1,2,4), c(NULL), c(1,2), c(3,4,5,6), c(1), c(1,3)), 2,3)
#---------
[,1] [,2] [,3]
[1,] Numeric,3 Numeric,2 1
[2,] NULL Numeric,4 Numeric,2
Inspect the first element:
> Mlist <- matrix( list(c(1,2,4), c(NULL), c(1,2), c(3,4,5,6), c(1), c(1,3)), 2,3)
> Mlist[1,1]
[[1]]
[1] 1 2 4
> is.matrix(Mlist)
[1] TRUE
> class( Mlist[1,1] )
[1] "list"
Demonstration of creating "matrix of lists" from a list:
> will.become.a.matrix <- list(c(1,2,4), c(NULL), c(1,2), c(3,4,5,6), c(1), c(1,3))
> is.matrix(will.become.a.matrix)
[1] FALSE
> dim(will.become.a.matrix) <- c(2,3)
> is.matrix(will.become.a.matrix)
[1] TRUE
> dim(will.become.a.matrix)
[1] 2 3
> class(will.become.a.matrix[1,1])
[1] "list"
Further requested demonstration:
A<- list(); F=list() E=list()
A[1]<-c(3) ; F[[1]]<-numeric(0); E[[1]]<-numeric(0)
A[2]<-c(1) ; F[2]<-c(1) ; E[2]<-c(1)
A[3]<-c(1) ; F[3]<-c(2) ; E[[3]]<-numeric(0)
A[[4]]<-list(1,3) ;F[[4]]<-numeric(0) ; E[[4]]<-numeric(0)
A[5]<-c(4) ; F[5]<-c(4) ; E[5]<-c(4)
Mlist= c(A,F,E)
M <- matrix(Mlist, length(A), 3)
#=====================================
> M
[,1] [,2] [,3]
[1,] 3 Numeric,0 Numeric,0
[2,] 1 1 1
[3,] 1 2 Numeric,0
[4,] List,2 Numeric,0 Numeric,0
[5,] 4 4 4
You asked (in comments) "....is there a way to define number of column and rows , but not the element itself because they are unknown?"
Answered (initially in comments)
b<-matrix(rep(list(), 6),nrow = 2, ncol =3)
#.... then replace the NULL items with values.
# Need to use "[[": for assignment (which your 'Update 1' did not
# ....and your Update2 only did for some but not all of the assignments.)
b[[1]] <- c(1,2,3,4)
Create a list of multiple matrices with list instead of using a for loop
The simplest solution would be to add each loop result to a list:
matlist <- list()
for (i in 1:ntime) {
matlist[[i]] = assign(paste0("matrix_out",i), PRECIPITATION[,,i]*mask)
}
Right, I forgot about the matrices saved to the environment. You can eliminate that with:
matlist <- list()
for (i in 1:ntime) {
matlist[[i]] = PRECIPITATION[,,i]*mask
names(matlist)[i] = paste0("matrix_out",i)
}
So the stand-alone matrices are not created
Related Topics
R: How to Filter a Timestamp by Hour and Minute
How to Force Ggplot's Geom_Tile to Fill Every Facet
Shiny Datatable in Landscape Orientation
How to Append R Data Frame into Existing Excel Without Overwriting
Using Dplyr to Group_By and Conditionally Mutate a Dataframe by Group
Include Link to Local HTML File in Datatable in Shiny
Visualizing Distance Between Nodes According to Weights - with R
Extract First N Digits from a String
How to Use Different Font Sizes in Ggplot Facet Wrap Labels
How to Use Custom Cross Validation Folds with Xgboost
How to Predict Survival Probabilities in R
Install Previous Versions of R on Ubuntu
Creating Categorical Variables from Mutually Exclusive Dummy Variables
How to Draw Arrow in Ggplot2 with Annotation
Find Max Per Group and Return Another Column
R: Apply Function to Matrix with Elements of Vector as Argument