【发布时间】:2021-12-17 22:47:55
【问题描述】:
我正在尝试在一系列正负值上使用 for 循环,然后绘制结果。但是,我无法让 R 不绘制正确的值,因为负值似乎搞砸了索引。
更准确地说,我正在运行的代码是:
# Setup objects
R = (1:20)
rejection = rep(NA, 20)
t = seq(from = -10, to = 10, by = 1)
avg_rej_freq = rep(NA, 21)
# Test a hypothesis for each possible value of x and each replication
for (x in t) {
for (r in R) {
# Generate 1 observation from N(x,1)
y = rnorm(1, x, 1)
# Take the average of this observation
avg_y = mean(y)
# Test this observation using the test we found in part a
if (avg_y >= 1 + pnorm(.95))
{rejection[r] = 1}
if (y < 1 + pnorm(.95))
{rejection[r] = 0}
}
# Calculate the average rejection frequency across the 20 samples
avg_rej_freq[x] = mean(rejection)
}
# Plot the different values of x against the average rejection frequency
plot(t, avg_rej_freq)
生成的图表应如下所示
# Define the rejection probability for n=1
rej_prob = function(x)(1-pnorm(1-x+qnorm(0.95)))
# Plot it
curve(rej_prob,from = -10, to = 10, xlab = expression(theta),
ylab = "Rejection probability")
...但是我的代码显然有问题,将图表上的正值向左移动。
任何有关如何解决此问题的帮助将不胜感激!
【问题讨论】:
标签: r