[R] Using apply with more than one matrix

Waichler, Scott R Scott.Waichler at pnnl.gov
Thu May 1 17:00:09 CEST 2014


> > Sapply or mapply may work, I haven't used these much and will try to
> learn better how to use them.  Your use of sapply looks good; but I'm
> trying to understand if and how I can bring in the operation on a1.  This
> doesn't work:
> >
> > evaluate <- function(idx) {
> >  ind.not.na <- which(!is.na(a1[idx,])) ]))  # doesn't work; improper
> > indexing for a1
> >  if(length(ind.not.na) > 0) {
> >    return(condition1*(a1[idx,ind.not.na[1]] + m2[idx]))  # doesn't
> > work; improper indexing for a1  } } vec <- sapply(seq(length(m2)),
> > evaluate)
> 
> Are we to assume that the length of `which(!is.na(a1[idx,])) ]))` is
> guaranteed to equal the length of the two other matrices? If not then what
> sort of relationships should be assumed?

ind.not.na is just a vector that could be any length.  It is a selection on the vector a1[i,j,].  I want to get the first element of that selection.  The key relationship is that the dimensions of the matrices and the first two dimensions of the 3d arrays are the same.  That is, i and j have the same range for all of them.  

Scott



More information about the R-help mailing list