我的后勤地图R函数有什么问题 [英] What's wrong with my R function of logistic map

查看:60
本文介绍了我的后勤地图R函数有什么问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently learning R at school and I'm stuck with this question:

这是我的代码:

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)

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

Whenever I run it it gives back the error:

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

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

Can someone help me figure out what I'm doing wrong? Many thanks!

推荐答案

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

Your way of initializing the output vector in your function is incorrect. Use N <- numeric(tmax + 1) instead of length(N) <- tmax. Vectors in R uses 1-based indexing not 0-based indexing.

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

这篇关于我的后勤地图R函数有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆