Am looking at say 3-dimensional array M: M<-dim(3,3,3)
I want to find an efficient way to populate M with the following rule:
M[i,j,k] = i/10 + j^2 + sqrt(k),
ideally without having to write a loop with a for statemenet.
For clarification, there is a simple way to accomplishing this if M were 2-dimensional. If i wanted to have
M[i,j] = i/10 + j^2,
then i could just do
M<-row(M)/10 + col(M)*col(M)
Is there something equivalent for 3-or-higher dimensional arrays?
@James’s answer is better, but I think the narrow answer to your question (multidimensional equivalent of
row()/col()) isslice.index…It would be a good idea if someone (I or someone else) posted a suggestion on the
r-devellist to makeslice.indexa “See also” entry on?row/?col…Alternatively (similar to @flodel’s new answer):