lundi 30 janvier 2017

Error in an if statement not reponding to clauses

I need to make a file which will write basic statistics questions for a question bank.

I wrote a script in r in which in each cycle of a for statement a data set is created and then converted to a single frequency vector. Then a question is selected with the following pattern: "q1" in cycle 1, "q2" in cycle 2, "q3" in cycle 3, "q1" in cycle 4, "q2" in cycle 5, etc. This is performed by an if statement.

The questions and answers are written into a file named with the date.

The problem is that the answers are wrong, the program sometimes keeps the last value and I can't figure it out why. This is a sample output:

The code I'm using is the following:

Aaa <- function() 
{ 
  Qt  <<- readline(prompt="Iterations:")  
  } 

Aaa() 

##### Create file to sink to:#################
Date.<-Sys.Date()
Date.<-format(Date., format="%Y%m%d")
Archivo<- paste(Date.,".txt",sep="")

##### Create iterations ######################

sink(Archivo, append=FALSE)
cat("PRUEBA")
cat("\n")
sink(NULL)

for (i in 1:Qt){
  j<-(i/3-trunc(i/3))*3  

sink(Archivo, append=TRUE)

##### Generación de variables y cálculos #####  

  x<-round(rnorm(400,55,12),0)

  cuts<-seq(10.5,100.5,9)
  x<-x[x>10]
  x<-x[x<101]
  Table.<-hist(x,breaks = cuts,plot = FALSE)$counts
  Class. <- sample(3:9,1)

if (j==0) {
  Qstn <- paste("What is cum sum for class ",Class.,"?",sep="")
  Answ<-cumsum(Table.)[Class.]
} else if (j==1) {
  Qstn <- paste("What % of data corresponds to class ",Class.,"?",sep="")
  Answ<-Table.[Class.]/sum(Table.)*100 
} else if (j==2) {
  Qstn <- paste("Cummulative percent for class ",Class.,"?",sep="")
  Answ<-cumsum(Table.)[Class.]/length(x)*100 
}

##### List of questions #####
  cat(Table.,sep=", ")
    cat("\nQuestion ",i,":\n", 
      Qstn,"?\n",
    "=",Answ,"\n",
    "\n\n\n",
    sep="")

sink(NULL)
}

Aucun commentaire:

Enregistrer un commentaire