Possible Duplicate:
Randomly selecting values from an existing matrix after adding a vector (in R)
This is a follow up to my question from last week and can be found here. I wasn't sure if it was appropriate to post this question in the same place, or to post it as a new question.
Okay, last time I asked about randomly removing values from a matrix after binding a new vector to it. The answers were very useful, but I have found a bug when I am using a non square matrix. I have been running the code in a loop and taking the sum of the matrix each time to ensure that it is working properly, but I have found that the sum varies, which would imply that the code is sometimes selecting the wrong value in the matrix (I want it to only select and replace ones).
Here is the code:
mat1<-matrix(c(1,0,1,0, 0,1,1,1, 1,0,0,0, 1,0,0,1, 1,1,1,1, 0,0,0,1),byrow=F, nrow=4)
I.vec<-c(0,1,1,1,0,0)
foo <- function(mat, vec) {
nr <- nrow(mat)
nc <- ncol(mat)
cols <- which(vec == 1L)
rows <- sapply(seq_along(cols),
function(x, mat, cols) {
ones <- which(mat[,cols[x]] == 1L)
sample(ones, 1)
}, mat = mat, cols = cols)
ind <- (nr*(cols-1)) + rows
mat[ind] <- 0
mat <- rbind(mat, vec)
rownames(mat) <- NULL
mat
}
set.seed(2)
for (j in 1:1000){ #run this vector through the simulations
I.vec2=sample(I.vec,replace=FALSE) #randomize interactions
temp=foo(mat1,I.vec2) #run foo function
prop=sum(temp)
print.table(prop)
}
In this case, sometimes the sum of the matrix is 13 and sometimes it is 14, when it should always be = sum(mat1) = 13.
I've tried to pick apart the code, and I think everything is working correctly except for the rows function, which, admittedly, I do not fully understand.