Reputation: 137
I'm trying to write a function in r that includes a named argument with three options. (What I want to do is find the area in the right tail of a normal curve, the left tail, or both tails.) Is this possible? I've come up with this, but I get an error when I try it with right=BOTH
.
st.pnorm<-function(x,µ,ø,right=c('TRUE','FALSE','BOTH')){
if (right==FALSE) return({pnorm((x-µ)/ø)})
if (right==TRUE) return({1-(pnorm((x-µ)/ø))})
if (right==BOTH) return({x*2})
}
st.pnorm(19.4,11,8.4,right='BOTH')
Error in st.pnorm(19.4, 11, 8.4, right = "BOTH") :
object 'BOTH' not found
(I know x*2 isn't correct, but I want to see if I can get this to work structurally before I actually write that code.)
Upvotes: 5
Views: 10819
Reputation: 106
That your named argument has three options suggests that strings (as you've set it up) are a better way to go than Boolean values. Calling the parameter tail, instead of right, would make your intent clearer.
st.pnorm<-function(x,µ,ø,tail=c('right','left','both')){
if (tail=='left') return({pnorm((x-µ)/ø)})
if (tail=='right') return({1-(pnorm((x-µ)/ø))})
if (tail=='both') return({x*2})
}
Upvotes: 1
Reputation: 1360
st.pnorm<-function(x,µ,ø,right=TRUE){
if (right==FALSE) return({pnorm((x-µ)/ø)})
if (right==TRUE) return({1-(pnorm((x-µ)/ø))})
if (right=="BOTH") return({x*2})
}
TRUE
and FALSE
should be enclosed in quotes while BOTH
does need to be, hence if (right=="BOTH")
. Also with right=TRUE
you are declaring a default value to the TRUE
.
EDIT
As @KonradRudolph points out in the comments, the if
statement is checking if, what is inside the brackets, is TRUE
or not. If it is TRUE
then it will action otherwise it will skip. Therefore as right
takes on TRUE
or FALSE
the above could be re written as the following:
st.pnorm<-function(x,µ,ø,right=TRUE){
if (!right) return({pnorm((x-µ)/ø)})
if (right) return({1-(pnorm((x-µ)/ø))})
if (right=="BOTH") return({x*2})
}
Where !
acts as the not operator.
Upvotes: 4