Hi all,

I've written a function for a simulation which will - in general operation without being specific to the simulation scenario, duplicate or delete columns from a matrix based on two values which determine how many as a proportion of the matrix: the two values are always between 0.01 and 0.99:

Dup.Dels <- function(matrix, values){

  p.dup <- ceiling(ncol(matrix)*as.numeric(values[1])) #Determine how many columns to be duplicated.

  p.del <- ceiling(ncol(matrix)*as.numeric(values[2])) # Determine how many columns to be deleted.

  dups <- sample(ncol(matrix), p.dup, replace=FALSE) # Randomly choose columns to be duplicated.

  dels <- sample(ncol(matrix), p.del, replace=FALSE) # Randomly choose columns to be deleted.

  matrix.new <- cbind(matrix.new, matrix[,dups]) # Duplicate columns.

  matrix.new <- matrix.new[,-dels] # Delete columns.

  return(matrix.new)

}

I have a list of matrices of different column numbers and I apply the function like so (the values are in a matrix):
The lapply goes down the matrix list, and down the matrix with the 'values' in, applying the function.

New.Matrices <- lapply(seq(Matrices), function(i) Dup.Dels(Matrices[[i]], Values[i,]))

Now the weird thing is, if I test this with data and run this function. It appears to work exactly how I want it to, yet when it is called from the simulation loop I get:

Error: subscript out of bounds

So I open up all my .R files, load all my functions and open the simulation loop, go through each line, sending it to the R interpreter one by one, function by function. I get to the lapply line above, and it works! For some reason it works when I spoon feed my simulation loop line by line, but if I call the function to start up the simulation and run it, it will hit that function and tell me the subscript is out of bounds. Commenting out the call to the function in the simulation allows the rest of the simulation to execute perfectly.

Does anybody know why I would get this strange behaviour with this code? - writing it, testing it like by line with some starting data the simulation actually uses, it works fine, even going through the entire sim step by step, it works fine. Closing it all up and running the simulation by function call however it hits an error. Running through it with debug() and browser() it also hits this error at the same point - something is up with this function. I can't figure out, as far as I can tell my indexing in the lapply line is correct, both for operating on every element of the list "Matrix, and going down the rows of the matrix storing the two "values".



Thanks,
Ben W.

UEA (ENV) b.ward@uea.ac.uk
The Sainsbury Laboratory ben.ward@sainsbury-laboratory.ac.uk


	[[alternative HTML version deleted]]

