Rorita_Tai
Rorita_Tai

Reputation: 33

How can i build a for function for matrix?

Now i have a list like below:

mylist
[[1]]
[1] 0 1 0 1 1 0 0 1 0

[[2]]
[1] 0 1 0 1 0 1 0 1 1
...

I would like to make every list into a 3*3 matrix by a for loop function like:

for (i in 1:N){
m[i]=matrix(mylist[[i]],nrow=3,ncol=3,byrow=TRUE)

}

But it doesn't work out?

What else i can do ?

Thanks for helping in advance!

Upvotes: 0

Views: 49

Answers (2)

IRTFM
IRTFM

Reputation: 263301

m=list()
for (i in 1:length(mylist) ){
m[[i]] = matrix( mylist[[i]], nrow=3, ncol=3, byrow=TRUE)
}

> m
[[1]]
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    1    0    1
[3,]    1    1    1

[[2]]
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    1    0    1
[3,]    0    1    1

Upvotes: 0

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193507

You don't need a for loop for that. You can use lapply:

## First, make up some sample data
set.seed(1)
mylist <- replicate(2, sample(0:1, 9, TRUE), FALSE)

## Let's work on a copy in case you need the original
m <- mylist 
m
# [[1]]
# [1] 0 0 1 1 0 1 1 1 1
# 
# [[2]]
# [1] 0 0 0 1 0 1 0 1 1

## Here's the actual transformation
m[] <- lapply(m, matrix, nrow = 3, byrow = TRUE)
m
# [[1]]
#      [,1] [,2] [,3]
# [1,]    0    0    1
# [2,]    1    0    1
# [3,]    1    1    1
# 
# [[2]]
#      [,1] [,2] [,3]
# [1,]    0    0    0
# [2,]    1    0    1
# [3,]    0    1    1

Upvotes: 3

Related Questions