【问题标题】:Creating a Table out of a While Loop in R在 R 中的 While 循环中创建表
【发布时间】:2018-10-18 11:03:10
【问题描述】:

我正在尝试从 while 循环中创建一个表。基本上,我想创建一个 while 循环,其中 r 的值增加 1 并重复此操作,直到满足不等式。但除此之外,我想将这些值组合成一个包含三列的表:r 的值、w 的值和 rhs 的值(四舍五入到小数点后 3 位)。

```{r}
al = 0.10; n = 30; a = 3; b = 5; r = 2; int = 8; h = (int/2); msE = 19.19
table = function(MSE, V, H, alpha = al, r = 2){
  rhs = h^2*r/((V-1)*MSE)
  w = qf(alpha, V-1, V*(r-1), lower.tail = FALSE)
  g = data.frame(r, round(w, 3), round(rhs, 3))
  while(w > rhs){
    r = r+1
    rhs = h^2*r/((V-1)*MSE)
    w = qf(alpha, V-1, V*(r-1), lower.tail = FALSE)
    g = data.frame(r, round(w, 3), round(rhs, 3))
  }
  rbind(g)
}
table(MSE = msE, V = a*b, H = h)
```

我认为它会像这样,但这只会在循环结束之前打印出 r 的最后一个值(它在 26 处结束),这会导致一个只有一行的“表”。我想要一个有 24 行的表(因为它从 r = 2 开始)。

任何帮助将不胜感激!

【问题讨论】:

  • table() 是一个现有的 R 函数,重新定义它可能不是一个好主意,而是选择一个不同的名称
  • 好电话,我将它重命名为别的东西(毕竟名字是微不足道的)。

标签: r loops while-loop


【解决方案1】:

也许这可能会有所帮助:

al = 0.10; n = 30; a = 3; b = 5; r = 2; int = 8; h = (int/2); msE = 19.19
table = function(MSE, V, H, alpha = al, r = 2){
  rhs = h^2*r/((V-1)*MSE)
  w = qf(alpha, V-1, V*(r-1), lower.tail = FALSE)
  g = data.frame(r, round(w, 3), round(rhs, 3))
  gn = data.frame(r, round(w, 3), round(rhs, 3))
  while(w > rhs){
    r = r+1
    rhs = h^2*r/((V-1)*MSE)
    w = qf(alpha, V-1, V*(r-1), lower.tail = FALSE)
    g = data.frame(r, round(w, 3), round(rhs, 3))
    gn <- rbind(gn,g)
  }
return(gn)
}
table(MSE = msE, V = a*b, H = h)

【讨论】:

  • 您可能想解释是什么让您的版本工作,与 OP 的初始尝试相比
  • 这正是我所需要的。谢谢!
【解决方案2】:

一种略有不同的方法,无需临时数据框和rbind()。在代码中注释。

# your parameters
al <- 0.10; n <- 30; a <- 3; b <- 5; int <- 8; h <- (int/2); msE <- 19.19

# your function definition (name changed to avoid confusion / conflict with existing R function)
tabula <- function(MSE, V, H, alpha = al, r = 2)
{
    g <- data.frame( N = 0, W = 1, RHS = 0 )        # initiate data frame, values set
                                                    # so that the while condition is met

    # the while function populates the data frame cell by cell,
    # eliminating the need for an interim data.frame and rbind()
    while( g[ r - 1, "W" ] > g[ r - 1, "RHS" ] )    # check condition in the last data frame row
    {                                               # write values in a new row
        g[ r, "N" ] <- r
        g[ r, "W" ] <- round( qf( alpha, V - 1, V * ( r - 1 ), lower.tail = FALSE ), 3 )
        g[ r, "RHS" ] <- round( h^2 * r / ( ( V - 1 ) * MSE ), 3 )
        r <- r + 1                                  # increment row counter
    }
    return( g[ -1, ] )                              # return the data frame, removing the initial row
}

tabula( MSE = msE, V = a * b, H = h )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 2011-03-05
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2021-02-04
    • 2014-03-25
    • 1970-01-01
    相关资源
    最近更新 更多