I'm writing some code to perform some game theory simulations. My "world" has several states (say 2 in my case), it also has several players (again, 2), and each player has a matrix of payouts (2 by 2).
I tried creating the following multi-dimensional array in R:
U = array(2,2,2,2)
U[1][1] = cbind(c(0.7,0.3),c(0.3,0.7))
and I receive the following error:
number of items to replace is not a multiple of replacement length
I can move to using a list, in which each item will be a list of two items, A and B, where A and B are 2x2 matrices. However, I think that performing operations on the lists will become slowly annoying and vectorization will be hard.
Is there a suggestion on the proper implementation or an explanation on why the above code doesn't work?
Update: Apparently the proper syntax would be:
U[1,1, , ] = cbind(c(0.7,0.3),c(0.3,0.7))
My question still stands - which is better, multi-dimensional vectors or list of tuples?
Thanks,
This code cannot possible work, and you should at least try it for yourself:
array(2,2,2,2) ## results in unused argument error
I think you want a 4D array
U <- array(0, dim = c(2,2,2,2))
and then to assign to a 2D portion use R's ?Extract syntax
U[1,1,,] <- cbind(c(0.7,0.3),c(0.3,0.7))
The code U[1][1]
can be understand in terms of U being treated as if were a vector with no "dim" attribute (just the numbers in a vector, no dimension structure). The first [1]
extracts the first element, returning a single element vector and the second [1]
in turn redundantly extracts the first element from that single element vector.
In terms of understanding what U[1,1,,]
is: this is a 2D matrix that is a subset of the 4D array U
, specified by taking the first slice from the first and second dimensions, and every slice from the third and fourth dimensions.
The error you see comes from the fact that you are trying to assign a 2D matrix into a single element of U
- but there's only one slot and the structure and size of the first element is different to the matrix you are trying to crush into it.
The singleton dimensions (first and second) that have only one slice from the extracted subset are dropped (by default) from the result. This can be avoided by specifying:
U[1, 1, , , drop = FALSE]
which would give a 4D array, but one with two "degenerate" dimensions i.e. [1, 1, 2, 2] where the first two are kind of redundant (but the sense of that really depends on your purpose). This part is not really relevant to the issue of assigning new values to a subset of the original array, but it might help your understanding.
Whether an array or a list is best for you depends on what you would like to do, so I'd recommended re-asking your question and focussing on those needs.
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