Imagine I have a function that gives the transition probability of going from state {x,y} to state {X, Y}: transition <- function(x,y,X,Y)
Imagine the x values can assume values in on a discrete set of points x_grid and y assume discrete values in y_grid, and I’d like to compute all possible transitions, e.g. fill out as a 2D matrix like this:
X1Y1 X2Y1 X3Y1 X1Y2 .... X3Y3
x1,y1
x2,y1
x3,y1
x1,y2
x2,y2
x3,y2
...
x3,y3
What’s the simplest way to loop over my function in R to generate this matrix?
A cumbersome approach with for loops
x_grid <- 1:3
y_grid <- 1:3
## dummy function
transition <- function(x,y,X,Y)
x == X && y == Y
nx <- length(x_grid)
ny <- length(y_grid)
T <- matrix(NA, ncol = nx * ny, nrow = nx * ny)
for(i in 1:nx)
for(j in 1:ny)
for(k in 1:nx)
for(l in 1:ny)
T[i+(j-1)*ny, k+(l-1)*ny] <-
transition(x_grid[i], y_grid[j], x_grid[k], y_grid[l])
Surely there’s a more efficient and more elegant way to do this in R?
For instance,
sapply(x_grid, function(x)
sapply(y_grid, function(y)
sapply(x_grid, function(X)
sapply(y_grid, function(Y)
transition(x,y,X,Y) ))))
works more efficiently but returns an object of the wrong shape. Turning the outermost apply into an lapply and then doing cbind on it’s elements corrects this, but feels very crude.
Here’s a wild shot in the dark. I hope it’s helpful: