【问题标题】:How to use a for loop over negative (and positive) values in R?如何在R中的负(和正)值上使用for循环?
【发布时间】: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


    【解决方案1】:

    是的,因为您怀疑负指数会导致问题。 R 不知道如何将某些东西作为“负优先”对象存储在向量中,所以它只是丢弃它们。相反,请尝试使用 seq_along 生成所有正索引的向量并循环遍历它们:

    # 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 seq_along(t)) {
      for (r in R) {
        # Generate 1 observation from N(x,1)
        # Now we ask for the value of t at index x rather than t directly
        y =  rnorm(1, t[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)
    

    产生以下情节:

    【讨论】:

      【解决方案2】:

      不知道为什么要使用 for 循环来模拟矢量化函数 pnrom(),但仍然纠正代码中的错误(检查 cmets):

      # 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)
          # no need to take average since you have a single observation
          # Test this observation using the test we found in part a
          rejection[r] = ifelse(y >= 1 + pnorm(.95), 1, 0)
        }
        # Calculate the average rejection frequency across the 20 samples
        # `R` vector index starts from 1, transform your x values s.t., negative values become positive
        avg_rej_freq[x-min(t)+1] = mean(rejection)
      }
      
      
      # 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")
      
      # plot your points
      points(t, avg_rej_freq, pch=19, col='red') 
      

      【讨论】:

        【解决方案3】:

        不知道为什么 for 循环等,你在做什么可以折叠成一行。其余代码取自@Sandipan Dey

        R <- 20
        t <- seq(from = -10, to = 10, by = 1)
        
        #All the for-loops collapsed into this one line:
        avg_rej_freq <- rowMeans(matrix(rnorm(R * length(t), t), 21) >= 1 + pnorm(.95))
        
        rej_prob <- function(x) 1 - pnorm(1 - x + qnorm(0.95))
        curve(rej_prob,from = -10, to = 10, xlab = expression(theta), 
                       ylab = "Rejection probability")
        
        # plot your points
        points(t, avg_rej_freq, pch=19, col='red') 
        

        【讨论】:

          猜你喜欢
          • 2018-11-22
          • 1970-01-01
          • 2019-03-11
          • 2014-11-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-16
          相关资源
          最近更新 更多