Mike Mike - 3 months ago 21
R Question

Multiple matrix outputs from a for loop

As usual, I feel I'm missing something horribly simple, but I'm trying to get a for loop to output me a number of versions of the results of another for loop.

The code:

#Create Species Vector
species.v <- letters[1:5]

#Matrix creation (Random)
start.matrix <- matrix(sample(species.v,25,replace=TRUE),
nrow=5,
ncol=5)

result.matrix <- vector("list",25)

for (i in 1:10) {
for (i in 1:50) {
in.dex <- sample(length(start.matrix),1)
start.matrix[in.dex] <- as.character(sample(start.matrix,1))
}

result.matrix[[i]] <- start.matrix
}


While the loop for index/sample/replacement is an extremely simplified version of what I'm doing, it has the same result. I'd then need to repeat this loop a number of times (in this example 10) and keep each output for later analysis/comparison.

I'd rather not do it through writing a new file (e.g. CSV) as I'll be doing my analysis in R anyway, but I can't seem to get the actual output to multiple files to work.

In the above example I tried to create a "result.matrix" vector as a list, though if the output is easier as a matrix that's fine - I just kept getting


Error in result.matrix[[i]] <- start.matrix : more elements
supplied than there are to replace


returned when I had result.matrix set up as a 5x5 matrix (either empty or with stuff in).

Any help would be appreciated

Answer

The direct answer to your question, based on the description of your problem, is to fix your code in two places:

#Create Species Vector
species.v <- letters[1:5]

#Matrix creation (Random)
start.matrix <- matrix(sample(species.v,25,replace=TRUE),
                       nrow=5,
                       ncol=5)

result.matrix <- vector("list",10)  # Changed here

for (i in 1:10) {
  for (j in 1:50) {                 # Changed here
      in.dex <- sample(length(start.matrix),1)
      start.matrix[in.dex] <- as.character(sample(start.matrix,1))
  }    
  result.matrix[[i]] <- start.matrix
}