R: applying function over matrix and keeping matrix dimensions

前端 未结 4 535
再見小時候
再見小時候 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:10

    There's a slight refinement of Dason and Josh's solution using 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
    

提交回复
热议问题