I am writing a function in R that will compute a sum of squares between a binomial distribution and normal distribution and display the data as a function of p
Here is what I have:
First I generate a random binomial distribution with probability p (n=100)
random_binom<-rbinom(100,100,p)
Next, I find the probability that some random element has equal or less than the value np (the mean) and the standard deviation of sqrt(np(1-p)) according to the normal distribution
d_norm<-dnorm(random_binom,p*100,sqrt(100*p*(1-p)))
And then the probability that a random value in the distribution will have equal or less than the value of the mean according to the binomial distribution
d_binom<-dbinom(random_binom,100,p)
finally I subtract the two, take the square and return it.
result<-sum((d_norm-d_binom)^2)
return(result)
Now within the console, I created a function for all this:
myfunction:
function(p){
random_binom<-rbinom(100,100,p)
d_norm<-dnorm(random_binom,p*100,sqrt(100*p*(1-p)))
d_binom<-dbinom(random_binom,100,p)
result<-sum((d_norm-d_binom)^2)
return(result)
}
I want to pass in a vector for p where p<-(c(0:99)/100), but whenever I do that, the function returns
inf
rather than a vector of values. How can I get R to return a vector of values so that I can plot them? I have tried using lapply but that returns the data in a strange format:
[[95]]
[1] 0.01064091
[[96]]
[1] 0.01418807
[[97]]
[1] 0.02647295
[[98]]
[1] 0.05065813
[[99]]
[1] 0.1179141
[[100]]
[1] 0.7342808
meaning each element is contained another element, making it very difficult to graph.
The problem is that when
pis 0, your function will effectively do this:Maybe you want
p<-(c(1:99)/100)?lapplyreturns alist. You can useunlistto convert to an array. Suppose you assign the results of anlapplycall toL. Then, you can do this