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]
One way is to use apply on both rows and columns:
apply
apply(m,1:2,y) [,1] [,2] [,3] [,4] [,5] [1,] 2 NA 6 8 NA [2,] 3 5 NA 9 11
You can also do it with subscripting because == is already vectorized:
==
m[m %% 3 == 0] <- NA m <- m+1 m [,1] [,2] [,3] [,4] [,5] [1,] 2 NA 6 8 NA [2,] 3 5 NA 9 11