从 dnorm 获取平均值

Get mean value from dnorm

在下面的代码中,我试图从 normal1 和 normal2 中获取平均值,这样我就不必在 [=13= 中的 xintercept 值(3 和 0)中进行硬编码] 函数调用。

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")

我想在不向前声明变量并在初始 dnorm 调用中使用它们的情况下这样做。即

x1 <- 3
x2 <- 0

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

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

我是 R 的新手,对函数或其中的 returns 掌握得不是很好。

也许你可以尝试这样的事情

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")


}

所以你可以重新计算normal1和normal2函数。事实上,它们是用变量均值创建的,很容易用新值修改图。

m_1 <- 4
m_2 <- 2

plotter(m_1, m_2)

或者直接用新值执行 plotter() 函数。


游览

事实上,计算一个函数的均值,它的创建必然需要均值,这有点令人困惑,但并非不可能。

先把plotter函数稍微修改一下:

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

因此 normal1 函数在 plotter 函数之外可用。

现在我们来看看数学背景:函数的均值或期望值与密度乘以变量本身的曲线下面积重合。

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

其中 normal1 被解释为密度。

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

对于 m_1 <- 4 结果是,例如 (!):

4 with absolute error < 0.00019

请注意:将此方法与现有函数结合使用是一种经验方法。因此,可以通过最少的推导获得结果,但当然具有很高的准确性。