Search code examples
rnormal-distribution

Get mean value from dnorm


In the following code I am trying to get the mean value from normal1 and normal2 so that I don't have to hard code in the xintercept values (3 and 0) in the geom_vline function call.

normal1 <- function(x) {
    dnorm(x, 3, 3)
}

normal2 <- function(x) {
    dnorm(x, 0, 2)
}

plot + stat_function(fun = normal1) +
       stat_function(fun = normal2) + xlim(c(-10, 15)) +
       geom_vline(xintercept = 3, linetype = "dashed") +
       geom_vline(xintercept = 0, linetype = "dashed")

I'd like to do so without forward declaring the variable and using them in the initial dnorm call. ie

x1 <- 3
x2 <- 0

normal1 <- function(x) {
    dnorm(x, x1, 3)
}

normal2 <- function(x) {
    dnorm(x, x2, 2)
}

I am very new to R, and don't have a strong grasp of functions or returns in it.


Solution

  • Maybe you try something like this

    plotter <- function(m1,m2){
      normal1 <- function(x) {
        dnorm(x, m1, 3)
      }
    
      normal2 <- function(x) {
        dnorm(x, m2, 2)
      }
      ggplot(data = data.frame(x=0), mapping = aes(x=x))+ 
      stat_function(fun = normal1) +
        stat_function(fun = normal2) + xlim(-10, 15) +
        geom_vline(xintercept = m1, linetype = "dashed") +
        geom_vline(xintercept = m2, linetype = "dashed")
    
    
    }
    

    So you can re-calculate the normal1 and normal2 function. In fact they are created with a variable mean, it is easy to modify the plot with new values.

    m_1 <- 4
    m_2 <- 2
    
    plotter(m_1, m_2)
    

    or execute the plotter() function directly with new values.


    Excursion

    In fact, calculating the mean of a function which necessarily needs the mean for its creation is a bit confusing, but not impossible.

    First modify the plotter function a bit:

    normal1 <<- function(x) {
      dnorm(x, m1, 3)
    }
    

    so the normal1 function is available outside the plotter function.

    Now we have a look on the mathematical background: the mean or the expected value of a function coincides with the area under the curve of the density multiplied with the variable itself.

    mean1 <- function(x){
    normal1(x)*x
    }
    

    where normal1 is interpreted as the density.

    mean1_empirical <- integrate(mean1, lower = -Inf, upper = Inf)
    

    For m_1 <- 4 the result is, for example (!):

    4 with absolute error < 0.00019
    

    Please note: using this method with an existing function is an empirical approach. So it is possible to receive results with minimal derivation but of course a high accuracy.