Skip to content

for loop implementation in below problem

4 messages · Duncan Murdoch, Jim Lemon

#
Hi Goyani,
You are setting "PRE" to the return value of "if" which is one of TRUE
(1), FALSE(0) or NULL. Because GAY is always missing in your example,
"PRE" is always set to 1. Then you always want to pass 1 in the sample
list, and that will not assign anything to PRE. By correcting the "if"
clause and defining matrices that are unlikely to be singular, I can
run a "for" loop as follows:

selection.index<- function(ID, phen_mat, gen_mat, weight_mat, GAY){
 p<-as.matrix(phen_mat)
 g<-as.matrix(gen_mat)
 w<-as.matrix(weight_mat)
 bmat<- solve(phen_mat) %*% gen_mat %*% weight_mat
 GA<- 2.063 * t(bmat) %*% g %*% w / (t(bmat) %*% p %*% bmat)^0.5
 if(missing(GAY)) PRE<-(GA/GA) * 100
 else PRE<-(GA/GAY) * 100
 result<-list(ID=ID,b=matrix(round(bmat,4),nrow=1),
  GA=round(GA,4),PRE=round(PRE,4))
 return(data.frame(result))
}

pmat<-matrix(sample(1:16,16),4)
gmat<-matrix(sample(17:32),16,4)
wmat<-matrix(sample(1:4,4),4)

mi<-combn(1:4,2)
sc<-list()
for(i in 1:ncol(matindx)) {
 as.numeric(ID<-paste0(mi[,i]))
 sc[[i]]<-selection.index(ID,pmat[mi[,i],mi[,i]],gmat[mi[,i],mi[,i]],
  wmat[mi[,i]],1)
}

This produces output for me. Good luck with whatever you are doing with this.

Jim
On Mon, Mar 22, 2021 at 2:51 PM Goyani Zankrut <zankrut20 at gmail.com> wrote:
#
On 22/03/2021 1:59 a.m., Jim Lemon wrote:
That's not true at all.  The statement was

     PRE<- if(missing(GAY)){
       (GA/GA) * 100
     } else {
       (GA/GAY) * 100
     }

so the result is (GA/GA) * 100 or (GA/GAY)*100.
If that's true and GA isn't missing, the result will always be 100.

Duncan Murdoch
#
If he's setting PRE to the return value of "if", that is the logical
value of the expression in the if statement as far as I know. I think
that the expression within the else clause would be evaluated but not
assigned to anything and since it is within the loop, would just be
lost.

PRE<-ifelse(missing(GAY),(GA/GA)*100,(GA/GAY)*100)

would return either value depending upon whether GAY was missing.
That's what I get from the help pages.

Jim
On Mon, Mar 22, 2021 at 8:34 PM Duncan Murdoch <murdoch.duncan at gmail.com> wrote:
#
No, I am confounded, It does return the value of the expressions
within the respective braces, just like ifelse. Learn something every
day.

Jim
On Mon, Mar 22, 2021 at 9:35 PM Jim Lemon <drjimlemon at gmail.com> wrote: