This function can be thought of as a version of base::apply() that is guaranteed to return a object of the same dimensions as it was input. It also generally preserves attributes, as it's built on top of [<-.

modify_along_dim(X, which_dim, .f, ...)

modify_along_rows(X, .f, ...)

modify_along_cols(X, .f, ...)

Arguments

X

An array, or a list of arrays

which_dim

integer vector of dimensions to modify at

.f

a function or formula defining a function(same semantics as purrr::map()). The function must return either an array the same shape as it was passed, a vector of the same length, or a scalar, although the type of the returned object does not need to be the same as was passed in.

...

passed on to .f()

Value

An array, or if X was a list, a list of arrays of the same shape as was passed in.

Examples

x <- array(1:6, 1:3) modify_along_dim(x, 3, ~mean(.x))
#> , , 1 #> #> [,1] [,2] #> [1,] 1.5 1.5 #> #> , , 2 #> #> [,1] [,2] #> [1,] 3.5 3.5 #> #> , , 3 #> #> [,1] [,2] #> [1,] 5.5 5.5 #>
modify_along_dim(x, 3, ~.x/mean(.x))
#> , , 1 #> #> [,1] [,2] #> [1,] 0.6666667 1.333333 #> #> , , 2 #> #> [,1] [,2] #> [1,] 0.8571429 1.142857 #> #> , , 3 #> #> [,1] [,2] #> [1,] 0.9090909 1.090909 #>