mardi 8 juin 2021

How can I shorten the code with FOR and İF structure?

I am looking for another alternative code. Kodum çok uzun.

Question_No <-c(1,1,1,1,1,10,10,10,10,10,11,11,11,11,11)
Reply<-c("never","few","medium","much","complete",
             "never","few","medium","much","complete",
             "never","few","medium","much","complete")
Number_of_Answers<- c(7,1,12,13,18,6,2,12,10,21,6,2,13,11,19)
aa<- data.frame(Question_No,Reply,Number_of_Answers)
replace<- function(x)
    {Replys=x['Reply'] 
    if(Replys=="few"){return(2)}
    else if(Replys=="much"){return(4)} 
    else if(Replys=="never"){return(1)}
    else if(Replys=="medium"){return(3)}
    else {return(5)}}
  Replys<- apply(aa,MARGIN = 1,FUN = replace)
  aa['Replys']<-Replys
  aa= mutate(aa,NA_R = aa$Replys * aa$Number_of_Answers)

   aa$result = ifelse(aa$Question_No == 1,  sum(aa[1:5,5]),
                ifelse(aa$Question_No == 10, sum(aa[6:10,5]),
                ifelse(aa$Question_No == 11, sum(aa[11:15,5]),"n")))

My code is too long. Is there more useful code with For and IF instead of IFELSE?

Aucun commentaire:

Enregistrer un commentaire