I wrote the code below to generate a matrix containing something that is rather complicated for me. In this case, I determined that in the finished matrix there are 136 rows in the traffic jam and error.
I could write a function to calculate the number of rows of a matrix in advance, but the function would be a bit complicated. In this example, the number of rows in the matrix = ((4 * 3 + 1) + (3 * 3 + 1) + (2 * 3 + 1) + (1 * 3 + 1)) * 4.
Is there a simple and efficient way to create matrices in R without hard wiring the number of rows in a matrix expression? In other words, is there an easy way to let R just add a row to the matrix if necessary using for-loops?
I presented one solution that uses rbind on each pass through the loops, but this seems a bit confusing, and I was wondering if there could be a much easier solution.
Sorry if this question is redundant with an earlier question. I could not find a similar question using the search function on this site or using the Internet search engine today, although I think I found a similar question somewhere in the past.
Below are two sets of sample code, one of which uses rbind and the other where I used the trial version and error to set nrow = 136 in advance.
Thanks for any suggestions.
v1 <- 5 v2 <- 2 v3 <- 2 v4 <- (v1-1) my.matrix <- matrix(0, nrow=136, ncol=(v1+4) ) i = 1 for(a in 1:v2) { for(b in 1:v3) { for(c in 1:v4) { for(d in (c+1):v1) { if(d == (c+1)) ls = 4 else ls = 3 for(e in 1:ls) { my.matrix[i,c] = 1 if(d == (c+1)) my.matrix[i,d] = (e-1) else my.matrix[i,d] = e my.matrix[i,(v1+1)] = a my.matrix[i,(v1+2)] = b my.matrix[i,(v1+3)] = c my.matrix[i,(v1+4)] = d i <- i + 1 } } } } } my.matrix2 <- matrix(0, nrow=1, ncol=(v1+4) ) my.matrix3 <- matrix(0, nrow=1, ncol=(v1+4) ) i = 1 for(a in 1:v2) { for(b in 1:v3) { for(c in 1:v4) { for(d in (c+1):v1) { if(d == (c+1)) ls = 4 else ls = 3 for(e in 1:ls) { my.matrix2[1,c] = 1 if(d == (c+1)) my.matrix2[1,d] = (e-1) else my.matrix2[1,d] = e my.matrix2[1,(v1+1)] = a my.matrix2[1,(v1+2)] = b my.matrix2[1,(v1+3)] = c my.matrix2[1,(v1+4)] = d i <- i+1 if(i == 2) my.matrix3 <- my.matrix2 else my.matrix3 <- rbind(my.matrix3, my.matrix2) my.matrix2 <- matrix(0, nrow=1, ncol=(v1+4) ) } } } } } all.equal(my.matrix, my.matrix3)