I set up a 3 dimensinoal matrix of size 365x7x4.
x <- array(rep(1, 365*5*4), dim=c(365, 5, 4))
Now I would to use a for loop to fill each element with a value.
Lets say the value of each element should be sum of row, column and depth.
I guess this is relatively easy.
Thanks! best, F
Using a simpler example so we can see what is being done
the following code gives the requested output:
The above gives
Update: Using the example in @TimP’s Answer here I update the Answer to show how it can be done in a more R-like fashion.
Given
Replace elements of
arrwithi + j + kunlessk > 2, in which casej*k-iis used instead.Whilst it is tempting to stick with familiar idioms like looping, and contrary to popular belief loops are not inefficient in R, learning to think in a vectorised way will pay off many times over as you learn the language and start applying it to data analysis task.
Here are some timings on Fabian’s example:
and for a much larger (for my ickle laptop at least!) problem
but even that may be modest to small by today’s standards. You can see that the looping starts to become ever more uncompetitive because of the all the function calls required by that method.