Select subset of N-dimensional array with m-dimensional array?

Is it possible to select a subset of a three dimensional array with a two-dimensional binary array? I would like to be able to do this so that I can push values into the selection

For example I have an array dim(a) = (lat, long, time), and I want to select with dim(b) = (lat, long) which is an array full of TRUE/FALSE values. I want to be able to do something like:

> a <- array(c(1,2,3,4,5,6,7,8),c(2,2,2))
> b <- matrix(c(0,1,0,0), c(2,2))==TRUE
> a[[b]] <- 0
> a
, , 1
     [,1] [,2]
[1,]    1    3
[2,]    0    4

, , 2
     [,1] [,2]
[1,]    5    7
[2,]    0    8

Edit : ok, so this looks like a stupid question, as I just realised that it works exactly as stated above, if you use a[b] <- 0 (single brackets). But that only works if the dimension(s) you want to span are the ones at the end. So, to make it more interesting:

How can you do this if the dimension you want to span is the first or second dimension - eg. if dim(b)==(lat, years)?

Answers


R supports matrix subsetting of arrays with the [ operator (i.e. single bracket, not double - the double bracket will always only return a single element):

a[b] <- 0
a

, , 1

     [,1] [,2]
[1,]    1    3
[2,]    0    4

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    0    8

Notice that this is somewhat different from the result you specify in your question. In your question, the second element (i.e. bottom left element of the matrix) is 1, thus you would expect the second element of each array slice to be modified. (In other words not the first, as you have in your example.)


Need Your Help

How can I brighten the screen when opening an Activity in my Glass GDK immersion application?

android google-glass google-gdk

I have a GDK immersion application, where the launcher Activity acquires aSCREEN_DIM_WAKE_LOCK WakeLock. The app also has a Service which will receive chat messages and starts an Intent for an Act...