【问题标题】:Saving slope of each iteration from a loop in R从R中的循环中保存每次迭代的斜率
【发布时间】:2017-11-17 18:37:46
【问题描述】:

有数据变量(tcons 和 tleave)。尝试修改以下循环以提取/保存每次迭代的斜率并将斜率值绘制为直方图。不知道如何找到/保存斜坡。任何帮助将不胜感激。

plot(tcons,tleave, xlab="Time spent with conspecific (seconds)", ylab = 
"Time taken to leave a refuge (seconds)", main="Time spent with 
conspecific vs Time taken to leave refuge")

for(i in 1:10000) {print
  (abline(lm(sample(tcons)~tleave), col="lightgrey"))
    print(i)}

【问题讨论】:

  • 在调试代码之前,您可能希望使用for(i in 1:10) 而不是for(i in 1:10000)

标签: r for-loop iteration


【解决方案1】:

忽略错误的模型公式,您可以将所有系数保存到一个列表中,然后将该列表合并到一个 data.frame 中。现在每个系数都是一个变量。

N <- 10000
out <- vector("list", N)

for(i in 1:N) {
  mdl <- lm(sample(tcons)~tleave)
  out[i] <- coef(mdl)
}

out <- do.call(rbind, out)

hist(out[, 2]) # you can then plot histogram from slope, for example

【讨论】:

    【解决方案2】:
    model1 <- lm(sample(tcons)~tleave)
    slope <- model1$coefficients[2]
    

    然后根据需要循环并保存

    【讨论】:

      猜你喜欢
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2022-11-17
      • 1970-01-01
      相关资源
      最近更新 更多