0

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!

2
  • 1
    Hi. Welcome to Stackoverflow. From the R tag-wiki, R is a free, open-source programming language and software environment for statistical computing, bioinformatics, and graphics. Please supplement your question with a minimal reproducible example. For statistical questions please use stats.stackexchange.com. Also, do be sure to take the SO tour and at least brows through the SO help pages. Commented Dec 30, 2014 at 9:31
  • You should also read the error messages more carefully and post the complete error message rather than writing "doesn't work".. When you try to assign with an index on the LHS and the object being indexed doesn't exist, you get an error. Commented Dec 30, 2014 at 10:02

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.