【问题标题】:Implementing While loop for part of an array in R在R中为数组的一部分实现While循环
【发布时间】:2018-01-14 11:15:21
【问题描述】:

我有一个包含 10,000 行和 2 列的数组 x。我运行一个测试,然后我希望重复测试,直到测试大于 7.81,然后停止。这是旧代码。

x=matrix(runif(10000*2,0,1),10000,2)
test <- vector(mode="numeric", length=196)
i=0
while(max(test)<7.81 & 200+i*50<=nrow(x))
{
 y = x[seq(1,200+i*50),] # y contains the first 200+i*50 rows of x
 ts= runif(1,1,7.9) # random test statistic, enter yours here.
 test[i]= sum(ts)
 i=i+1}

我现在感兴趣的是:

我想运行测试直到它大于 7.81,但我想以不同的方式访问我的数组 x。在第一个实例中,我只想使用数组 x 的前 6,000 行。因此,我想将数组的条目增加 50。例如,第二次迭代我想使用第 50 行直到 6050、第三次迭代 x[100:6100]、第四次 x[150:6150] 等等。

【问题讨论】:

  • 你想要的是y &lt;- x[1:6000,],然后是y &lt;- x[50:6050,],然后是y &lt;- x[100:6100,]等等,对吗?
  • 是的,这就是我想要的

标签: arrays r loops while-loop


【解决方案1】:

我认为这可以满足您的需求。请注意,为了每次迭代有 6,000 行,您应该在第二次迭代中有 51 到 6,500 行,而不是 50 到 6,050 行。

x=matrix(runif(10000*2,0,1),10000,2)

test=0
i=0
while(max(test)<7.81 & (6000+i*50)<=nrow(x))
{
  y = x[seq(i*50+1,6000+i*50)] # y contains the first 200+i*50 rows of x
  ts= runif(1,1,7.9) # random test statistic, enter yours here.
  test[i]= sum(ts)
  i=i+1
}

可以在循环中加入这一行来验证:

print(paste0(i*50+1," to ", 6000+i*50, ", number of entries: ", 6000+i*50-(i*50+1)+1 ))

输出:

[1] "1 to 6000, number of entries: 6000"
[1] "51 to 6050, number of entries: 6000"
[1] "101 to 6100, number of entries: 6000"
[1] "151 to 6150, number of entries: 6000"
[1] "201 to 6200, number of entries: 6000"

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2015-12-24
    • 1970-01-01
    • 2021-06-29
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多