如何为矩阵构建for函数?

时间:2014-12-30 09:22:44

标签: r for-loop matrix

现在我有一个如下列表:

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

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

我想通过for循环函数将每个列表变成3 * 3矩阵,如:

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

}

但它没有成功吗?

我还能做什么?

感谢您提前帮助!

2 个答案:

答案 0 :(得分:3)

你不需要for循环。您可以使用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

答案 1 :(得分: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