【问题标题】:R: repeating for loop and counting resultR:重复for循环并计算结果
【发布时间】:2014-05-03 09:52:50
【问题描述】:

我有这个 for 循环,我需要重复(比如 1000 次),并计算 p.value 高于某个值的次数。我想我已经控制了计数部分,但我只是不知道如何重复循环以获得我可以使用的输出。

    leads <-list(lead_one, lead_two, lead_three, lead_four, lead_five, lead_six, lead_seven, lead_eight, lead_nine, lead_ten)

    for(i in 1:length(leads)){   
  (ks.test(sample(lead_en, 75), sample(leads[[i]], 75)))$p.value  
    }

帮助?

更新(更新#2:代码现在应该可以重现了):

我很抱歉没有提供足够的信息,我是编程新手,对于寻求编程帮助也是全新的。让我再尝试一次。我想在提前期向量 (lead_en) 上运行 ks.test,而不是“线索”中的所有提前期向量。我可以用上面发布的 for 循环来做到这一点。然后我想多次运行这个for循环来计算某个结果的次数。

我试过了(没有计数器):

lead_en <- c(4, 5, 3, 4, 5, 6, 7, 3, 4, 2, 3)
lead_one <- c(3, 4, 5, 2, 2, 5, 7, 8, 3, 2, 6)
lead_two <- c(4, 2, 5, 6, 3, 1, 5, 7, 5)
lead_three <- c(4, 3, 5, 5, 6, 7, 9, 9, 3, 3, 3)
lead_four <- c(5, 3, 5, 6, 3, 4, 5, 6)
lead_five <- c(4, 5, 3, 5, 6)
lead_six <- c(2, 3, 6, 9, 9, 5, 5, 6, 7, 4, 3, 3)
lead_seven <- c(3, 4, 5, 5, 6, 3, 3)
lead_eight <- c(2, 3, 3, 3, 3, 4, 5)
lead_nine <- c(5, 6, 7, 3, 3, 4)
lead_ten <- c(5, 3, 4, 5, 6, 7, 7)
leads <-list(lead_one, lead_two, lead_three, lead_four, lead_five, lead_six, lead_seven, lead_eight, lead_nine, lead_ten)


d <- 100 # number of replications
res = matrix(rep(0, nrow=10, ncol=d))

for (k in 1:length(d)){
  for(i in 1:length(leads)){   
 res[i, k] <-   print(ks.test(sample(lead_en, 75), sample(leads[[i]], 75)))$p.value    
  }
}

这不起作用。我希望这能澄清我正在尝试做的事情。

【问题讨论】:

  • leads_oneleads_two、三等是什么?
  • 向量列表。 Leads_one 等是提前期的向量。我想在lead_en和leads中的所有向量上运行ks.test。
  • 欢迎来到 SO。请read this
  • 感谢您提供额外信息,但该示例不是独立的,即我们没有您的数据。此外,which does not work 是对出现问题的相当模糊的描述。查看@RichardScriven 发布的链接,了解如何向我们提供您的数据。
  • 我添加了一些数据,应该可以重现。

标签: r for-loop


【解决方案1】:

试试:

 sapply(leads, function(x) ks.test(sample(lead_en, 75), sample(x, 75)))$p.value)

我想我无法提供更多帮助,因为您没有提供足够的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多