I keep getting inf values when i run a function over an array

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.

Answers


The problem is that when p is 0, your function will effectively do this:

dnorm(0, 0, 0)
[1] Inf

Maybe you want p<-(c(1:99)/100)?


lapply returns a list. You can use unlist to convert to an array. Suppose you assign the results of an lapply call to L. Then, you can do this

unlist(L)

Need Your Help

JPA/Criteria API - Like & equal problem

java jpa jpa-2.0 criteria-api

I'm trying to use Criteria API in my new project:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.