[R] vectorising ifelse()
Adaikalavan Ramasamy
ramasamy at cancer.org.uk
Fri Jul 22 12:20:02 CEST 2005
Does either 'zippo' or 'zappo' contain the values 1 or 2 ?
If so, then you cannot vectorize this code because you are changing the
values in 'new' at every iteration and potentially sampling a value from
new[ ,1] or new[ ,2] .
If not, then it might be possible to vectorize. Something along the
following untested lines
pos <- which( srow > 0 )
neg <- which( srow <= 0 )
new[pos ,1] <- new[ cbind(srow[pos] , zippo[pos]) ]
new[neg, 1] <- sample( 1:100, length(neg), prob=Y1, replace=TRUE )
and then repeat for filling in new[ ,2].
Am I correct in guessing that your srow and zippo are of the equal
length here and thus new is a square matrix.
Regards, Adai
On Fri, 2005-07-22 at 00:44 +0100, Federico Calboli wrote:
> Hi All,
>
> is there any chance of vectorising the two ifelse() statements in the
> following code:
>
> for(i in gp){
> new[i,1] = ifelse(srow[i]>0, new[srow[i],zippo[i]], sample(1:100, 1,
> prob =Y1, rep = T))
> new[i,2] = ifelse(drow[i]>0, new[drow[i]>0,zappo[i]], sample(1:100,
> 1, prob =Y1, rep = T))
> }
>
> Where I am forced to check if the value of drow and srow are >0 for each
> line... in practical terms, I am attributing haplotypes to a pedigree,
> so I have to give the haplotypes to the parents before I give them to
> the offspring. The vectors *zippo* and *zappo* are the chances of
> getting one or the other hap from the sire and dam respectively. *gp* is
> the vectors of non-ancestral animals. *new* is a two col matrix where
> the haps are stored.
>
> Cheers,
>
> Federico
>
More information about the R-help
mailing list