mercredi 4 octobre 2017

How to write a function for and for loop with embedded if else statement?

I have just started using R for a course I'm taking and it asked for integer values > 0 (argument1) and which will multiply values <25 and >75 by a set multiplier (argument 2) and the other elements by a different multiplier (argument 3).

I already have the previous h and s values:

h=sample(1:100,40)

s=c()
 for(i in 1:100){if(h[i]<25){s[i]<-h[i]*10}
else if(h[i]>75){s[i]<-h[i]*10}
else{s[i]<-h[i]*0.1}}
Error in if (h[i] < 25) { : missing value where TRUE/FALSE needed

The error message shows up in the above for loop but if I ignore it I still get the answer. I want but would not work in the function.

fun2<-function(x=s,arg1,arg2,arg3)
{w<-for(i in 1:100){if(h[i]>0){s[i]<-h[i]*arg1}else if(h[i]<25){s[i]<-
h[i]*arg2}
else if(h[i]>75){s[i]<-h[i]*arg2}
else{s[i]<-h[i]*arg3}}
return(w)}

fun2(arg1=10,arg2=3,arg3=10)
Error in if (h[i] > 0) { : missing value where TRUE/FALSE needed

I am unsure where to put the true/false statement in the equation.

Aucun commentaire:

Enregistrer un commentaire