1

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 !

2
  • 2
    outer only works on vectorized functions. (See ?Vectorize for a quick workaround ...) Commented Sep 16, 2020 at 16:04
  • @BenBolker , is there any other possibility that could work like mapply ? Commented Sep 16, 2020 at 16:06

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you a lot for precious help !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.