[R] Filling matrix elements with a function
Aimee Kopolow
alj27 at georgetown.edu
Tue Nov 6 05:11:59 CET 2012
Hi all,
I have a matrix simulating migration in a spatial model. I want to be
able to define movement (the values of m1, m2 and m3) as only != 0
between adjacent patches and contingent on certain conditions as
defined in the function.
Here is the code:
WET<-function(t) {everglades$precipitation[t]} #simply reads
precipitation data from a csv, value is numeric
AB<-function(WET,t) {ifelse(WET(t)>0, 0.0001, 0)}
BC<-function(WET,t) {ifelse(WET(t)>0, 0.0001, 0)}
NP<-4
m1 <- matrix(0, NP,NP)
m2 <- matrix(0,NP,NP)
m3 <- matrix(0,NP,NP)
for (i in 1:NP)
{
for (j in 1:NP)
{
if ((i%%sqrt(NP)) == 0 & i!=j)
{
if(j == i+sqrt(NP) | j == i-1 | j == i-sqrt(NP))
{
m1[j,i] <- AB
m1[i,j] <- AB
m2[j,i] <- 0.00025
m2[i,j] <- 0.00025
m3[j,i] <- BC
m3[i,j] <- BC
}
}
if (i%%sqrt(NP) == 1)
{
if(j == i+sqrt(NP) | j == i+1 | j == i-sqrt(NP) )
{
m1[j,i] <- AB
m1[i,j] <- AB
m2[j,i] <- 0.00025
m2[i,j] <- 0.00025
m3[j,i] <- BC
m3[i,j] <- BC
}
}
if (i%%sqrt(NP)!=0 & i%%sqrt(NP)!=1 & i!=j)
{
if(j == i+sqrt(NP) | j == i+1 | j == i-sqrt(NP) | j == i-1)
{
m1[j,i] <- AB
m1[i,j] <- AB
m2[j,i] <- 0.00025
m2[i,j] <- 0.00025
m3[j,i] <- BC
m3[i,j] <- BC
}
}
}
}
Please could somebody advise me as to where I'm going wrong and how to
get it right? I have tried several different permutations and can't
seem to do so. I tried googling keywords "inserting function as matrix
element" but couldn't find any advice online. I'm very inexperienced
at coding so apologies if this is very simple.
Thank you for any assistance you are able to give,
Aimee.
More information about the R-help
mailing list