# Functionasdfghjklöä

Hey guys, I have to write a function that is able to calculate all four types of confidence interval (of an average). The function should include the parameter "case/type", with that the user can state for which type the confidence interval should be calculated.

I´ve got the idea that I have to define the four types first and name them accordingly and then I have to work with "if". But I don´t know what I am supposed to pack into the function. Is there someone who might help me?

Edit: I have specified four types of CI:

1. normally distributed, variance known
2. normally distributed, variance unknown
3. arbitrarily distributed, variance known, n>30
4. arbitrarily distributed, variance unknown, n>30

Now I guess I have to start with the function like this:

``````CI<-function(n,mean,sd,z){
if(Type1==TRUE){
mean(x)-qnorm(1-z/2)*(sd/sqrt(n))
mean(x)+qnorm(1-z/2)*(sd/sqrt(n))}
if(Type2==TRUE){
}}
``````

AND SO ON

Can I do it like that or have I used "if" or any other part of this function in a wrong way?

Best regards!

klaus

You are on the right path but your function lacks a few things.
Where is the Value of Type1 coming from?
Using the approach of setting Type1 = TRUE, you would have four variables, one for each type of CI. You could use a single variable and set its value to 1,2,3, or 4.
Your calculate the value `mean(x)-qnorm(1-z/2)*(sd/sqrt(n))` but you do not store that in a variable. How will you return that value from the function?

1 Like

Hey, thanks for the response. What if I try it like this:

``````CI<-function(n, mean, sd, z, type){
if(type=="normal_knownvariance"){
result<- mean(x)+c(-1,1)*qnorm(1-z/2)*(sd/sqrt(length(x))
} else if (type=="normal_unknownvariance"){
result<-mean(x)+c(-1,1)*qnorm(1-t/2)*(sqrt(var)/sqrt(length(x)))
} else if (type=="arbitrary_knownvariance_largen){
result<-mean(x)+c(-1,1)*qnorm(1-z/2)*(sd/sqrt(length(x)))
}else if (type=="arbitrary_unknownvariance_largen){
results<-mean(x)+c(-1,1)*qnorm(1-z/2)*(sqrt(var)/sqrt(length(x)))
}
return(result)
}
``````

Best Regards!

Yes that looks good except that the variables x and var are not defined. If they are defined in the environment that calls the function, the function will work, I think. I have not run the code, so there might be other problems but the general idea seems correct.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.