I'm trying to get a probability matrix from Poisson distribution using a vector of Lambda. what i want to get:
x<-seq(1,3,1)
Lambda<-seq(1,2,0.5)
dpois(x,Lambda[1])
[1] 0.36787944 0.18393972 0.06131324
dpois(x,Lambda[2])
[1] 0.3346952 0.2510214 0.1255107
dpois(x,Lambda[3])
[1] 0.2706706 0.2706706 0.1804470
when i do it like this:
dpois(x,Lambda)
[1] 0.3678794 0.2510214 0.1804470
i get the probs of x[i] with Lambda[i] and not for each lambda all probs of x
i want to know how to do it without using a loop...
in other words i would like to insert into dpois() two vectors for x and lambda, and get all the possible probability combination.
For creating pairs of all combinations of vectors you need to use expand.grid
function.
x <- seq(1, 3, 1)
Lambda <- seq(1, 2, 0.5)
grid <- expand.grid(x=x, Lambda=Lambda)
dpois(grid$x, grid$Lambda)
When R does something in vectorized way, it aligns and repeats shorter vectors to longest vector as in the example below:
> cbind(1:5, 1:8, 1:2, 1:3)
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 2 2 2
[3,] 3 3 1 3
[4,] 4 4 2 1
[5,] 5 5 1 2
[6,] 1 6 2 3
[7,] 2 7 1 1
[8,] 3 8 2 2
So the other way around would be to make your longest vector long enough so that the shorter one will be able to repeat enough times so to create all the combinations:
> x <- 1:2
> y <- 1:3
> cbind(x,y)
x y
[1,] 1 1
[2,] 2 2
[3,] 1 3
Warning message:
In cbind(x, y) :
number of rows of result is not a multiple of vector length (arg 1)
> cbind(rep(x, each=length(y)), y)
y
[1,] 1 1
[2,] 1 2
[3,] 1 3
[4,] 2 1
[5,] 2 2
[6,] 2 3