从R

时间:2017-11-17 18:37:47

标签: r for-loop iteration

拥有数据变量(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)}

2 个答案:

答案 0 :(得分:1)

model1 <- lm(sample(tcons)~tleave)
slope <- model1$coefficients[2]

然后循环并根据需要保存

答案 1 :(得分: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