【问题标题】:What's wrong with my R function of logistic map我的逻辑图 R 函数有什么问题
【发布时间】:2019-03-05 11:18:18
【问题描述】:

我目前正在学校学习 R,但我一直被这个问题困扰:

这是我的代码:

logistic.map <- function(N0, r, K, tmax) {
  length(N) <- tmax
  N[1] <- N0
  for (i in 1:tmax) N[i+1] <- N[i] + r * N[i] * (1 - N[i] / K)
  return(list(t = 0:tmax, N = tmax))
  }

r1 <- logistic.map(2,0.2,100,50)
r2 <- logistic.map(2,2.2,100,50)
r3 <- logistic.map(2,2.9,100,50)

xlab="Years"
ylab="Population"
plot(r1$t, r1$N, xlab=xlab, ylab=ylab)
plot(r2$t, r2$N, xlab=xlab, ylab=ylab)
plot(r3$t, r3$N, xlab=xlab, ylab=ylab)

每当我运行它时,它都会返回错误:

Error in logistic.map(2, 0.2, 100, 50) : object 'N' not found
Error in logistic.map(2, 2.2, 100, 50) : object 'N' not found
Error in logistic.map(2, 2.9, 100, 50) : object 'N' not found

有人可以帮我弄清楚我做错了什么吗?非常感谢!

【问题讨论】:

  • 另外,您的函数在 for 循环中计算 N 的值,然后不返回它们。应该是return(list(t = 0:tmax, N = N))

标签: r function loops for-loop plot


【解决方案1】:

您在函数中初始化输出向量的方式不正确。使用N &lt;- numeric(tmax + 1) 而不是length(N) &lt;- tmax。 R 中的向量使用基于 1 的索引而不是基于 0 的索引。

关于返回值,使用return(list(t = 0:tmax, N = N))

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 2017-04-12
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    相关资源
    最近更新 更多