使用R在for循环中操作多个矩阵

时间:2013-05-15 19:35:50

标签: r

我有1000个名为A1, A2, A3,...A1000.

的矩阵

在for循环中,我想简单地取每个矩阵的colMeans():

for (i in 1:1000){
means[i,]<-colMeans(A1)
}

我想为每个矩阵Ax执行此操作。有没有办法在for循环中放置Ai而不是A1?

4 个答案:

答案 0 :(得分:3)

所以,一种方法是:

for (i in 1:1000){
 means[i,]<-colMeans(get(paste('A', i, sep = '')))
}

但我认为这忽略了一些评论的意思,即你可能不得不这样做:

csvs = lapply(list.files('.', pattern = 'A*.csv'), function(fname) {
   read.csv(fname)
})

然后您的问题的答案是:

means = lapply(csvs, colMeans)

答案 1 :(得分:1)

我不完全理解,但也许您已将每个矩阵分配给不同的变量名称?这不是最好的结构,但你可以从中恢复:

# Simulate the awful data structure.
matrix.names<-paste0('A',1:1000)
for (name in matrix.names) assign(name,matrix(rnorm(9),ncol=3))

# Pull it into an appropriate list
list.of.matrices<-lapply(matrix.names,get)

# Calculate the column means
column.mean.by.matrix<-sapply(list.of.matrices,colMeans)

答案 2 :(得分:0)

您最初的问题是要求“for循环”解决方案。但是,有一种简单的方法可以获得所需的 结果如果我们使用'apply'函数。

或许将矩阵放入列表中,然后应用函数将证明是值得的。

### Create matrices
A1 <- matrix(1:4,   nrow = 2, ncol = 2)
A2 <- matrix(5:9,   nrow = 2, ncol = 2)
A3 <- matrix(11:14, nrow = 2, ncol = 2)

### Create a vector of names
names <- paste0('A', 1:3)

### Create a list of matrices, and assign names
list <- lapply(names, get)
names(list) <- names

### Apply the function 'colMeans' to every matrix in our list
sapply(list, colMeans)

我希望这很有用!

答案 3 :(得分:0)

正如其他人所写,使用列表可能是您的最佳选择。首先,您需要将1000个矩阵放在一个列表中,最容易使用for循环完成(参见上面的几个帖子)。下一步更重要:使用另一个for循环来计算摘要统计信息(colMeans)。

要通过R对象应用for循环,通常可以执行以下两个选项之一:

  1. 通过索引循环:例如:

    for(i in 1:10){head(mat [i])} #simplistic example

  2. 循环&#34;直接&#34;

    for(i in mat){print(i)} #simplistic example

  3. 在循环浏览R列表的情况下,FIRST选项将更容易设置。以下是适合您的示例的想法:

    column_means <- rep(NA,1000) #empty vector to store column means
    
    for (i in 1:length(list_of_matrices)){
    mat <- list_of_matrices[[i]] #temporarily store individual matrices
    ##be sure also to use double brackets!
    column_means <- c(column_means, colMeans(mat))