[R] IFELSE across large array?
Ray Brownrigg
ray at mcs.vuw.ac.nz
Wed Nov 24 00:55:13 CET 2004
> From: "Liaw, Andy" <andy_liaw at merck.com>
> Date: Tue, 23 Nov 2004 12:28:48 -0500
>
> I'll give it half a crack:
>
> Steps a through c can be done via nested ifelse(), treating A and M as
> vectors (as they really are). Step d is the hard one. I'd write a simple
> Fortran code and use .Fortran() for that.
>
> I don't see how any of the *apply() functions can help here, as your
> operations are element-wise, not dimension-wise.
>
> Andy
>
The original message mentions that the value 10 is actually "NODATA",
and if one recodes 10 as NA, steps a) to c) become trivial, namely:
A[A == 10] <- NA
M[M == 10] <- NA
return(A + M - 1)
Then if step d) is performed first (i.e. appropriate values in A are
replaced by the 'most common neighbour' [perhaps using
round(mean(.., na.rm=T))] this still works, but would have to be repeated
for each replication (the third dimension).
Ray Brownrigg
> > From: Sander Oom
> >
> > Dear all,
> >
> > As our previous email did not get any response, we try again with a
> > reformulated question!
> >
> > We are trying to do something which needs an efficient loop
> > over a huge
> > array, possibly functions such as apply and related (tapply,
> > lapply...?), but can't really understand syntax and examples in
> > practice...i.e. cant' make it work.
> >
> > to be more specific:
> > we are trying to apply a mask to a 3D array.
> > By this I mean that when "overlaying" [i.e. comparing element
> > by element]
> > the mask on to the array the mask should change array
> > elements according to
> > the values of both array and mask elements
> >
> > the mask has two values: 1 and 10.
> >
> > the array elements have 3 values: 0, 1, or 10
> >
> > sticking for the moment to the single 2d array case
> >
> > for example:
> > [A= array] 10 0 10 1 10 0
> > 1 10 1 0 0 10
> >
> > [ M=mask] 1 10 10 1 1 1
> > 10 1 1 1 10 10
> >
> > I would like the array elements to:
> >
> > a) IF A(ij) !=10 and Mij = 1
> > leave A(ij) unchanged
> >
> > b) IF A(ij) != 10 and M(ij) =10
> > change A(ij) to M(ij) i.e mask value (10)
> >
> > c)IF A(ij) = 10 and M(ij) = 10
> > leave (Aij) unchanged
> >
> > d) IF A(ij) = 10 and M(ij) !=10
> > replace A(ij) with the majority value in the
> > 8-neighborhood
> >
> > (or whatever if it is an edge element) BUT ignoring 10s in this
> > neighborhood (i.e. with either 1 or 0, whichever is in majority)
> >
> > because the array is 3d I would like to repeat the thing with
> > all the k
> > elements (2d sub-arrays) of the array in question, using the
> > same mask for
> > al k elements
> >
> > Would you be able to suggest a strategy to do this?
> >
> > thanks very much
> >
> > Alessandro and Sander.
More information about the R-help
mailing list