R: applying function over matrix and keeping matrix dimensions

前端 未结 4 540
再見小時候
再見小時候 2021-02-01 15:21

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]         


        
4条回答
  •  失恋的感觉
    2021-02-01 16:01

    One way is to use apply on both rows and columns:

    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
    

提交回复
热议问题