R: applying function over matrix and keeping matrix dimensions

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

    For this specific example you can just do something like this

    > # Create some fake data
    > mat <- matrix(1:16, 4, 4)
    > # Set all elements divisible by 3 to NA
    > mat[mat %% 3 == 0] <- NA
    > # Add 1 to all non NA elements
    > mat <- mat + 1
    > mat
         [,1] [,2] [,3] [,4]
    [1,]    2    6   NA   14
    [2,]    3   NA   11   15
    [3,]   NA    8   12   NA
    [4,]    5    9   NA   17
    

提交回复
热议问题