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?
Indexing multi-dimensional arrays Multi-dimensional arrays are indexed in GAUSS the same way that matrices are indexed, using square brackets [] . Scanning above, you can see that the value of the element at the intersection of the third row and second column of x1 is 8.
Accessing 2D Array Elements In Java, when accessing the element from a 2D array using arr[first][second] , the first index can be thought of as the desired row, and the second index is used for the desired column. Just like 1D arrays, 2D arrays are indexed starting at 0 .
Arrays are the R data objects which can store data in more than two dimensions. For example: If we create an array of dimensions (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3 columns. These types of arrays are called Multidimensional Arrays.
We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
@James's answer is better, but I think the narrow answer to your question (multidimensional equivalent of row()/col()
) is slice.index
...
M<- array(dim=c(3,3,3))
slice.index(M,1)/10+slice.index(M,2)^2+sqrt(slice.index(M,3))
It would be a good idea if someone (I or someone else) posted a suggestion on the r-devel
list to make slice.index
a "See also" entry on ?row
/?col
...
Alternatively (similar to @flodel's new answer):
d <- do.call(expand.grid,lapply(dim(M),seq)) ## create data.frame of indices
v <- with(d,Var1/10+Var2^2+sqrt(Var3)) ## default names Var1, ... Varn
dim(v) <- dim(M) ## reshape into array
How about using nested outer
s?
outer(1:3/10,outer((1:3)^2,sqrt(1:3),"+"),"+")
, , 1
[,1] [,2] [,3]
[1,] 2.1 5.1 10.1
[2,] 2.2 5.2 10.2
[3,] 2.3 5.3 10.3
, , 2
[,1] [,2] [,3]
[1,] 2.514214 5.514214 10.51421
[2,] 2.614214 5.614214 10.61421
[3,] 2.714214 5.714214 10.71421
, , 3
[,1] [,2] [,3]
[1,] 2.832051 5.832051 10.83205
[2,] 2.932051 5.932051 10.93205
[3,] 3.032051 6.032051 11.03205
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With