map function

Hello,

I have a function P1(p,Q0) filling a matrix as I want :

P1<-function(p,Q0){
  B=matrix(0,Q0+1,Q0+1)
  for (i in 1:(Q0)){
    B[i,i]=(1-p)*(1-p)+p*p
    B[i,i+1]= p*(1-p)
    B[i+1,i]=p*(1-p)
  }
  B[1,1]=1-p
  B[1,2]=p
  B[Q0+1,Q0]=p*(1-p)
  B[Q0+1,Q0+1]=1-p*(1-p)
  return(B) }

If I want specific values for p, and all the corresponding matrices, I enter

p=seq(0.1,0.9,0.1)
Q0=6
map(p,P1(p,Q0))

and I get the error "Error in B[i,i]=(1-p)(1-p)+pp :
number of items to replace is not a multiple of replacement length".

whereas I get no error when trying manually each value of p.
Can you help me on that ?
Thanks.

You havent linked the object to be iterated over to the function to perform each time. Try

map(p,~P1(.x,Q0))

Note the tilde(~) syntax and the use of .x (or .) which represent the place where every element of p will be introduced at each call

Thanks. Indeed, that solves the problem. I'll try to see documentation a bit deeper next time for such a problem.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.