Skip to contents

The setapply() function applies a functions over the rows or columns of a mutable_atomic matrix, through pass-by-reference semantics.

The setapply() is a bit faster and uses less memory than apply.

Usage

setapply(x, MARGIN, FUN)

Arguments

x

a mutable_atomic 2-dimensional array (i.e. a matrix).
Arrays of other than 2 dimensions are not supported.

MARGIN

a single integer scalar, giving the subscript to apply the function over.
1 indicates rows, 2 indicates columns.

FUN

the function to be applied.
The function must return a vector of the same type of x, and the appropriate length (i.e. length ncol(x) when MARGIN == 1 or length nrow(x) when MARGIN == 2).

Value

Returns: VOID. This function modifies the object by reference.
Do NOT use assignment like x <- setapply(x, ...).
Since this function returns void, you'll just get NULL.

Examples


# re-order elements matrix by reference ====
x <- mutable_atomic(1:20, dim = c(5,4))
print(x)
#>      [,1] [,2] [,3] [,4]
#> [1,]    1    6   11   16
#> [2,]    2    7   12   17
#> [3,]    3    8   13   18
#> [4,]    4    9   14   19
#> [5,]    5   10   15   20
#> mutable_atomic 
#> typeof:  integer 
setapply(x, 1, FUN = \(x)x[c(4,1,3,2)])
print(x)
#>      [,1] [,2] [,3] [,4]
#> [1,]   16    1   11    6
#> [2,]   17    2   12    7
#> [3,]   18    3   13    8
#> [4,]   19    4   14    9
#> [5,]   20    5   15   10
#> mutable_atomic 
#> typeof:  integer 


# sort elements of matrix by reference ====
x <- mutable_atomic(20:1, dim = c(5,4))
print(x)
#>      [,1] [,2] [,3] [,4]
#> [1,]   20   15   10    5
#> [2,]   19   14    9    4
#> [3,]   18   13    8    3
#> [4,]   17   12    7    2
#> [5,]   16   11    6    1
#> mutable_atomic 
#> typeof:  integer 
setapply(x, 2, FUN = sort)
print(x)
#>      [,1] [,2] [,3] [,4]
#> [1,]   16   11    6    1
#> [2,]   17   12    7    2
#> [3,]   18   13    8    3
#> [4,]   19   14    9    4
#> [5,]   20   15   10    5
#> mutable_atomic 
#> typeof:  integer