Tou Mou
Tou Mou

Reputation: 1274

Outer not working for a function with several arguments?

I had developped the following function that return boolean values (0 or 1) :

lanchester<-function(time_range=c(0,T=30*60),delta=0.001 ,r=0.1,b=0.8,R_0=30,B_0=30){
R=R_0
B=B_0
result=matrix(data=c("R","B","p1","p2"),ncol=4)
for ( i in seq (1,floor(T/delta))){
R_d=-b*R*B*delta
B_d=-r*R*delta
p1=-R_d/(R+B)
p2=-B_d/(R+B)
 

x=sample(c(p1,p2),1,rep=TRUE)

if ( x==p1) {
R=R-1
B=B
} else if ( x==p2) {
R=R
    B=B-1
    }  
    result=rbind(result,c(R,B,p1,p2))
    if (!all(c(R,B,p1,p2)>0)){
    break
    }
    }
    
    m=nrow(result)
    
    if ( result[m,1]>result[m,2]) {
    return(0)
    } else {
    return(1)
    }
        
    }

 

 - second part : simulation

r1<-seq(0.1,0.9,0.1)
b1<-seq(0.1,0.9,0.1)
m <- outer (
   r1,      
   b1,      
   function (r1, b1)   lanchester(time_range=c(0,T=30*60),delta=0.001,r=r1,b=b1,R_0=30,B_0=30)
)
print(m)

Depending on r1 and b1 pairs , the ouput could be something like :

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
 [1,]    1    1    1    1    1    1    1    1    1
 [2,]    1    1    1    1    1    1    1    0    1
 [3,]    1    0    1    1    1    1    1    1    1
 [4,]    1    1    1    0    1    0    1    1    1
 [5,]    1    0    1    1    0    0    1    1    1
 [6,]    0    1    0    1    1    1    0    1    0
 [7,]    0    0    0    1    1    1    1    1    1
 [8,]    1    0    1    0    1    1    1    1    1
 [9,]    1    1    1    1    0    1    0    1    1

Here i'm trying to compute the lanchester() function for several possibilities of r and b arguments. This function lanchester() returns either 0 or 1 at once . As a result , the matrix m will be a matrix of zeros or ones with dimension equal to length(r)*length(b).

The problem here is that the outer function gives an error !

Thank you for help in advance !

Upvotes: 1

Views: 36

Answers (1)

akrun
akrun

Reputation: 887048

As @BenBolker mentioned in the comments, Vectorize can be wrapped around the function to make it working

lanchester_vec <- Vectorize(function(r, b) {
          lanchester(time_range=c(0,T=30*60),delta=0.001,r, b, R_0=30, B_0=30)})
outer (r1, b1, lanchester_vec)
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# [1,]    1    0    0    1    1    1    1    1    1
# [2,]    1    1    0    0    1    0    1    1    1
# [3,]    1    1    1    1    0    0    0    1    1
# [4,]    1    1    1    1    1    0    1    1    1
# [5,]    0    1    0    1    1    1    0    1    0
# [6,]    0    0    1    1    1    1    1    0    0
# [7,]    1    1    0    1    0    0    1    0    0
# [8,]    1    1    0    1    1    0    0    1    0
# [9,]    1    1    1    0    1    1    1    0    1

Upvotes: 1

Related Questions