[R] Confused by code?

Rui Barradas ruipbarradas at sapo.pt
Mon Sep 24 19:34:21 CEST 2012


Hello,

Inline.
Em 24-09-2012 15:31, Bazman76 escreveu:
> Thanks Rui Barrudas and Peter Alspach,
>
> I understand better now:
>
> x<-matrix(c(1,0,0,0,2,0,0,0,2),nrow=3)
>   y<-matrix(c(7,8,9,1,5,10,1,1,0),nrow=3)
>   z<-matrix(c(0,1,0,0,0,0,6,0,0),nrow=3)
>   x[z]<-y[z]
>   viewData(x)
>
> produces an x matrix
>
> 7   0   0
> 0   2   0
> 0   10 2
>
> which makes sense the first element of y 7 is inserted into z in slot x[1]
> and the and 6th element of y 10 is slotted into the x[6].
>
>
> However the original code runs like this:
>
> mI<- mRU(de.d, de.nP)>de.CR
> mPV[mI]<mP[mI]
>
> where mPv and MP are both (de.d, de.nP) matrices.
>
> and
>
> mRU<-function(m,n){
>               return(array(runif(m*n), dim=c(m,n)))
> }
>
> i.e. it returns an array of m*n random numbers uniformly distributed between
> 0 and 1.
>
> de.CR is a fixed value say 0.8.
>
> So mI<- mRU(de.d, de.NP)>de.CR returns a de.d*de.nP array where each
> element is 1 is its more than 0.8 and zero otherwise.
>
> So in this case element mPv[1] will be repeatedly filled with the value of
> mP[1] and all other elements will remain unaffected?
>
> Is this correct?

Yes and no, it should return a logical matrix, not a numeric one. Since 
it seems to be returning numbers 0/1, you can use as.logical like I've 
shown in my first post, or, maybe better,

mI<- which(mRU(de.d, de.nP) > de.CR, arr.ind = TRUE)

Like this you'll have an index matrix, whose purpose is precisely what 
its names says, to index. Matrices.
(I'm also a bit confused as to why the logical condition is returning 
numbers, are you sure of that?)

Anyway, the right way would be to index 'mPV' using a logical or an 
index matrix.

Hope this helps,

Rui Barradas
>
> If so I am still confused as this is not what I thought was supposed to by
> happening but I know that the code overall does its job correctly?
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Confused-by-code-tp4643946p4644010.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at 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.




More information about the R-help mailing list