[R] function in R for my exercise
Thomthom
rime.thomas at gmail.com
Wed Jan 4 16:45:32 CET 2012
Hi R helpers!
I have a question. I'm trying to create a function for an exercise. Here are
the arguments I should include:
x and y are numeric
z is a name ("plus","minus","multiply","divide")
and swap is logical.
Here is what the function should do:
When z="plus", then x+y is performed and so on for the other z names. It
should give a NA when the z argument doesn't correspond to something mention
before.
When swap =TRUE, then y must be on the left side of the equation (y/x
instead of x/y).
So far, I managed to get something worked for the first part of the body
function (typing "plus" performes indeed an addition...) but I couldn't get
how to make the second part working. Any suggestion?
Here is the code I have so far:
myFunc<- function(x,y,z,swap)
{ res= NULL
if(z =="plus") res=x+y
else if(z=="minus") res=x-y
else if(z== "multiply") res=x*y
else if(z=="divide") res=x/y
else res<-NA
return(res)}
Then, I tried to include some lines to take this "swap" function into
account by "splitting" somehow my function in 2:
myFunc<- function(x,y,z,swap)
{ res1= NULL
res2=NULL
if(z =="plus") res1=x+y
else if(z=="minus") res1=x-y
else if(z== "multiply") res1=x*y
else if(z=="divide") res1=x/y
else res1<-NA
if(z =="plus") res2=y+x
else if(z=="minus") res2=y-x
else if(z== "multiply") res2=y*x
else if(z=="divide") res2=y/x
else res2<-NA
if (swap<-T) return(res2)
else return(res1)
}
Any suggestions would be more than appreciated! I already thank you!
And happy new year! (that may be redundant to most of you I know ^^)
Thomas
--
View this message in context: http://r.789695.n4.nabble.com/function-in-R-for-my-exercise-tp4261710p4261710.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list