Estimate normal distribution from dnorm in R The function dnorm(x) in R gives you the value of the probability density function in the points x of a certain normal distribution (mean = 0 and SD = 1 by default), returning a vector of the same length than x.
However, I want to do the opposite: given a vector that approximates a probability density function (like the result of dnorm), I want to get the mean and standard deviation of the normal distribution represented by that given probability density.
Code example of what I would like to do:
pdf = dnorm(seq(-3,3,0.1), mean = 0, sd=1)
## get_normal would be supposes to return an list/vector containing the mean and SD, which in this particular case should be close to 0 and 1 respectively.
var_parameters = get_normal(pdf)


A very simple, general-purpose solution:
First, write a function that
takes parameters as an input, and returns the different between the predicted PDF for those parameters and the actual PDF (I've used the sum of squared differences here).
Then, use optim() to find the parameters than minimise this function.
x = seq(-3,3,0.1)
pdf = dnorm(x, mean = -.5, sd = .2)
f = function(pars){
  pred_pdf = dnorm(x, mean = pars[1], sd = pars[2])
  err = sum((pdf - pred_pdf)^2)
}
result = optim(c(0, 1), f) # c(0, 1) are initial values
round(result$par, 3)
# [1] -0.5  0.2

