I am rather new to R and could use some basic help. I'd like to generate sums of two normal random variables (variance = 1 for each) as their means move apart and plot the results. The basic idea: if the means are sufficiently far apart, the distribution will be bimodal. Here's the code I'm trying:
x <- seq(-3, 3, length=500)
for(i in seq(0, 3, 0.25)) {
y <- dnorm(x, mean=0-i, sd=1)
z <- dnorm(x, mean=0+i, sd=1)
plot(x,y+z, type="l", xlim=c(-3,3))
}
Several questions:
Thank you in advance!
答案 0 :(得分:1)
使用基本R功能进行此操作并不困难。我们首先定义一个函数f
来计算混合物法线的密度:
## `x` is an evaluation grid
## `dev` is deviation of mean from 0
f <- function (x, dev) {
(dnorm(x, -dev) + dnorm(x, dev)) / 2
}
然后我们使用sapply
循环遍历各种dev
以获得相应的密度:
## `dev` sequence to test
dev <- seq(0, 3, 0.25)
## evaluation grid; extending `c(-1, 1) * max(dev)` by 4 standard deviation
x <- seq(-max(dev) -4, max(dev) + 4, by = 0.1)
## density matrix
X <- sapply (dev, f, x = x)
最后我们使用matplot
进行绘图:
matplot(x, X, type = "l", lty = 1)
更多解释
在sapply
期间,x
未更改,而我们每次迭代时都会尝试dev
的一个元素。就像
X <- matrix(0, nrow = length(x), ncol = length(dev))
for (i in 1:length(dev)) X[, i] <- f(x, dev[i])
matplot(x, X)
会针对X
逐一绘制x
列。