I want to create different matrices in a loop and then combine (either cbind or rbind) them. But the following codes doesn’t work. Why not? And how to fix it?
dependent = matrix(c(30,184,6,106), 2, 2, byrow=T)
independent = c(160,166)
expected = numeric()
{for(i in 1:length(independent))
a = dependent*independent[i]/sum(independent)
expected = cbind(expected,a)}
This gives:
expected
[,1] [,2]
[1,] 15.276074 93.69325
[2,] 3.055215 53.97546
This is the result of only using the final iteration of the for loop. So the result is like only 166 is used, but 160 isn’t.
A few comments:
Your
forloop brackets are in the wrong place. You have:instead you should have:
When you construct a
forloop and ommit the brackets, only the first line after theforstatement is used.You can make your
forloop more efficient by saving the result ofsum(independent)since that doesn’t change with each iteration, i.e.In fact you can vectorise the whole calculation