dimanche 1 mai 2016

R loop and if else

I would like to assign variable 'ax' with a value in looping. My code is :

 ax<-0
 for (i in i:4){
 if(i%%4==1)
 {
    ax[i]<-"one"
 }
 else if(i%%4==2)
 {
     ax[i]<-"two"
 }
 else if(i%%4==3)
 {
     ax[i]<-"three"
 }
else
 {
     ax[i]<-"four"
 }

}

I expect I got ax[1], ax[2], ax[3], and ax[4] ,

"one"    "two"     "three"     "four"

but I got :

"0"    NA     NA     "four"

This is just a try, a real code are much more longer. but the 0nly main problem is about assigning value to respective array variable. Anything wrong with this?

here I add the real code

#library(sqldf)
n = 4
a=0
b=0
c=0
d=0
e=0
f=0
g=0
h=0

Sui_Q1_STS<-0
Sui_Q1_TS<-0
Sui_Q1_S<-0
Sui_Q1_SS<-0
Sui_Q2_STS<-0
Sui_Q2_TS<-0
Sui_Q2_S<-0
Sui_Q2_SS<-0
for (i in 1:n){

 if(i%%4==1)
 {
a<-sqldf("SELECT count([X.0]) from testes where [X.0]='Sangat Tidak Setuju' and (StartDate like '%11/05/2015 00:%' or StartDate like '%11/05/2015 01:%' or StartDate like '%11/05/2015 02:%' or StartDate like '%11/05/2015 03:%' or StartDate like '%11/05/2015 04:%' or StartDate like '%11/05/2015 05:%' or StartDate like '%11/05/2015 06:00%')")
#b c d e f g and h are also sqldf
Sui_Q1_STS[i]<-as.numeric(a)
Sui_Q1_TS[i]<-as.numeric(b)
Sui_Q1_S[i]<-as.numeric(c)
Sui_Q1_SS[i]<-as.numeric(d)
Sui_Q2_STS[i]<-as.numeric(e)
Sui_Q2_TS[i]<-as.numeric(f)
Sui_Q2_S[i]<-as.numeric(g)
Sui_Q2_SS[i]<-as.numeric(h)


Sui_Q1<-list()
Sui_Q1[[i]]<-cbind(Sui_Q1_STS[i],Sui_Q1_TS[i],Sui_Q1_S[i],Sui_Q1_SS[i])
Sui_Q2<-list()
Sui_Q2[[i]]<-cbind(Sui_Q2_STS[i],Sui_Q2_TS[i],Sui_Q2_S[i],Sui_Q2_SS[i])
Total[i]<-Sui_Q1[[i]][,1]+Sui_Q1[[i]][,2]+Sui_Q1[[i]][,3]+Sui_Q1[[i]][,4]
}
   else if(i%%4==2){

  #only different in SQL
   }
   else if(i%%4==3){

  #only different in SQL
}
   else if(i%%4==0){

   #only different in SQL
}

}

Aucun commentaire:

Enregistrer un commentaire