So I want to apply a function over a matrix in R. This works really intuitively for simple functions:
> (function(x)x*x)(matrix(1:10, nrow=2)) [,1] [,2] [,3]
There's a slight refinement of Dason and Josh's solution using ifelse.
ifelse
mat <- matrix(1:16, 4, 4) ifelse(mat %% 3 == 0, NA, mat + 1) [,1] [,2] [,3] [,4] [1,] 2 6 NA 14 [2,] 3 NA 11 15 [3,] NA 8 12 NA [4,] 5 9 NA 17