Can someone check my code to see why this message pops up "Error: could not find function "N1""

StackOverflow https://stackoverflow.com/questions/16051410

  •  04-04-2022
  •  | 
  •  

Question

I know its a simple fix but can someone please take a look at it:

a12= 0
a21= 0
K1= 1000
K2= 600
r1= 0.2
r2= 0.1
N1= ((K1 - a12*K2)/(1 - a12*a21))
N2= ((K2 - a21*K1)/(1 - a21*a12))
for(t in 1:80){
  N1[t+1]= N1(t) + r1*N1(t)*(K1 - N1 - a12*N2)/K1
  N2[t+1]= N2(t) + r2*N2(t)*(K2 - N2 - a21*N1)/K2
}
## Error: could not find function "N1"

Corrected Code:

N1= rep(0,80)
N2= rep(0,80)
a12= 0
a21= 0
K1= 1000
K2= 600
r1= 0.2
r2= 0.1
N1[1]= ((K1 - a12*K2)/(1 - a12*a21))
N2[1]= ((K2 - a21*K1)/(1 - a21*a12))
for(t in 1:80){
N1[t+1]= N1[t] + r1*N1[t]*(K1 - N1[t] - a12*N2[t])/K1
N2[t+1]= N2[t] + r2*N2[t]*(K2 - N2[t] - a21*N1[t])/K2
}
plot(1:81, N1, type="l", lwd=3, xlab="Time")
lines(1:81, N2, lwd=3, col='red')

When I ran my plots where I changed the values for a12 and a21 they looked like what I might expect since they modeled competitiveness between two species.

The three models I'm running:

no competition-        a12=0     a21=0
stable coexistence-    a12=0.25  a21=0.1
competitive exclusion- a12=0.25  a21=0.75
Was it helpful?

Solution

@e4e5f4 is correct in that your main problem is that you are using ( round brackets were you need [ square brackets.

However, in addition, you have an issue inside your for loop:

 # this is a problem, even with brackets corrected
 N1[t+1]= N1[t] + r1*N1[t]*(K1 - N1 - a12*N2)/K1
 N1[t+1]= N1[t] + r1*N1[t]*(K1 - N1 - a12*N2)/K1
                                 ^        ^
                          N1 & N2 are vectors

Since most mathematical operations in R are vectorized, the value being assigned (ie, the right hand side of your equation) is a vector whose length is growing at every iteration.


The subsequent warnings you are seeing come from trying to assign multiple values (ie a vector) into a single element of a vector.

You will see the same error if you try

 foo <- c(17, 23, 31)
 foo[3] <- 1:10

You are getting 158 of these warnings because you are iterating.


You most likely want to index those values (likely with N1[[t]] or N1[[t-1]], etc)

OTHER TIPS

Replace N1(t) with N1[t]. Do the same for N2.

Note: I think you are using Matlab syntax for array indexing which is different from R syntax.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top