removing loop in array recalculation

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

removing loop in array recalculation

Colin Beale
Hi,

I'm looking for a more elegant (and faster) solution to my current
problem than the code at the end. I'm sure there is one, but can't think
where to look - any pointers would be very welcome. The problem is one
of resampling within an array. This array consists of 0s, 1s and NAs.
For each level of dimension z, I would like to rewrite the array such
that it looks up the values in the matrix on either side (through a
variable number of cells) and determines if there is a 1 in any of them
- if so, the new value is 1, otherwise 0. This process is repeated
across the entire matrix: I will obviously end up with a lot more 1s in
the new array than I did before. The code at the end works, but is very
slow for large arrays (it needs package (magic) to work). Any
suggestions/pointers would be gratefully recieved

Colin

An example dataset could be:

size = 1               #determines how many values to sample around the
focal
library (magic)    
set.seed(1)
A <- array (sample (c (0,0,0,1), 35, replace = T), dim = c (5,4,2))
    temp <- apad (apad (A, c (size,size,0)), c(size,size,0), post =
FALSE)  # pads array
    temp[,c (1, (4 + 2 * size)),] <- NA            # makes additional
rows/cols = NA
    temp[c (1, (5 + 2 * size)),,] <- NA

    for (y in 1: 5) {                               # recalculates
within size
      for (x in 1: 4) {
        for (z in 1: 2) {
          A[y,x,z] <- ifelse (sum (temp[(y):(y+2 * size),(x):(x+2 *
size),z], na.rm = TRUE) == 0, 0, 1)
        }
      }
    }

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html