R,我可以在循环中使用我在循环中创建的变量吗?

时间:2021-04-15 22:50:48

标签: r loops for-loop

我想知道如何修复我拥有的这段代码。我正在尝试绘制 11 个图并保存每个图的拟合信息,但是当我尝试绘制最佳拟合线时,出现以下错误:

Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) : 
  invalid a=, b= specification
In addition: Warning message:
In int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) :
  NAs introduced by coercion

这是我的代码:

for(n in 2:12){
  nam<-paste("fit", n, sep = "")
  assign(nam, lm(profilin[101:135,n]~profilin[101:135,1]))
  plot(profilin[101:135,1], profilin[101:135,n], ylim=c(200,450), xlab="Time", ylab="Flourecence", col=cl[n-1])
  abline(nam)
  legend("topleft", legend=c(colnames(profilin)[n]), col=c(cl[n-1]), lwd=1)
}

这里还有我的一些数据:

profilin <- structure(list(Time = c(1500L, 1515L, 1530L, 1545L, 1560L, 1575L, 
1590L, 1605L, 1620L, 1635L, 1650L, 1665L, 1680L, 1695L, 1710L
), ActinOnly = c(357.03, 353.37, 350.22, 367.78, 367.1, 361.02, 
374.11, 371.67, 371.84, 379.44, 375.77, 377.25, 372.13, 385.1, 
386.98), p0_5uM = c(341.37, 331.86, 341.82, 341.58, 349.91, 351.02, 
353.87, 354.51, 353.64, 342.91, 355.29, 351, 354.67, 361.42, 
363.92), p1uM = c(336.23, 335.37, 324.01, 347.67, 343.42, 343.42, 
330.55, 358.45, 335.15, 321.5, 342.23, 353.56, 337.57, 360.57, 
350.06)), row.names = 101:115, class = "data.frame")
cl <- rainbow(ncol(profilin)-1)

1 个答案:

答案 0 :(得分:0)

建议您将相关值存储在列表中。这使得在 R 中使用值变得更加容易,并且不会用一堆名称中带有索引的变量来混淆您的全局环境。您可以在此处使用 lapply

fit <- lapply(2:4, function(n) {
  rows <- as.character(101:135)
  model <- lm(profilin[rows,n]~profilin[rows,1])
  plot(profilin[rows,1], profilin[rows,n], ylim=c(200,450), xlab="Time", ylab="Flourecence", col=cl[n-1])
  abline(model)
  legend("topleft", legend=c(colnames(profilin)[n]), col=c(cl[n-1]), lwd=1)
  model # this will be the return value
})

现在 fit 将是您所有模型的列表。然后,您可以使用 sapply(fit, nobs) 轻松获得每个模型的观察数量或使用 sapply(fit, coef)

获得所有系数