Is the following what you want?   It works for vectors or arrays of
any number of dimensions.  It assumes that the dimensions of the
grids are the same.

> grid1 <- c(1,2,NA,3,NA)
> grid2 <- c(101,102,103,104,NA)
> shouldCopy <- is.na(grid1) & !is.na(grid2)
> grid1[shouldCopy] <- grid2[shouldCopy]
> grid1
[1]   1   2 103   3  NA

You don't really need the ' & !is.na(grid2)': it just stops the copying
of NA elements of grid2 to NA elements of grid1.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On 
> Behalf
> Of Tom Roche
> Sent: Wednesday, May 08, 2013 5:38 PM
> To: r-help@r-project.org
> Subject: [R] [newbie] *apply to matching elements of n arrays?
> 
> 
> How to apply a function to all elements with the same indices in
> multiple arrays? E.g.:
> 
> I have two spatial grids defined the same way (i.e., same number of
> rows and columns--and dimensions, both 2D). Wherever both
> 
> * the value of an element i,j in the first grid is NA
> * the value of element i,j in the second grid is !NA
> 
> I want to copy the value from grid2[i,j] to grid1[i,j]. These matrices
> are not too big, so I'm able to do this with loops, but I know that's
> not "the R way." How to parallelize/vectorize this, e.g., with a
> single call to an 'apply'-type method? I believe I know how to operate
> on a single matrix (e.g., by using `apply` to traverse it by rows or
> cols), but not how to operate on multiple matrices.
> 
> Extra points for solutions that generalize to 3D or 4D (i.e., that allow
> applying the same function to identical elements in n arrays of n
> dimensions), since I will almost certainly need to work on arrays of
> those dimensions eventually.
> 
> Apologies if this is a FAQ, but a fair amount of googling via
> rseek.org is not finding an answer (perhaps because I'm not using the
> correct search terms). Feel free (in fact, be encouraged :-) to reply
> directly to me as well as the list (I'm on the digest, which gets huge).
> 
> TIA, Tom Roche <tom_ro...@pobox.com>
> 
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to