Pipe friendly dim<-(), with option to pad to necessary length. Also allows for filling the array using C style row-major semantics.

set_dim(
  x,
  new_dim,
  pad = getOption("listarrays.autopad_arrays_with", NULL),
  order = c("F", "C"),
  verbose = getOption("verbose")
)

Arguments

x

A vector or array to set dimensions on

new_dim

The desired dimensions (an integer(ish) vector)

pad

The value to pad the vector with. NULL (the default) performs no padding.

order

whether to use row-major (C) or column major (F) style semantics. The default, "F", corresponds to the default behavior of R's dim<-(), while "C" corresponds to the default behavior of reticulate::array_reshape(), numpy, reshaping semantics commonly encountered in the python world.

verbose

Whether to emit a message if padding. By default, FALSE.

Value

Object with dimensions set

See also

set_dim2(), `dim<-`(), reticulate::array_reshape()

Examples

set_dim(1:10, c(2, 5))
#> [,1] [,2] [,3] [,4] [,5] #> [1,] 1 3 5 7 9 #> [2,] 2 4 6 8 10
try( set_dim(1:7, c(2, 5)) ) # error by default, just like `dim<-`()
#> Error in dim(x) <- new_dim : #> dims [product 10] do not match the length of object [7]
set_dim(1:7, c(2, 5), pad = 99)
#> [,1] [,2] [,3] [,4] [,5] #> [1,] 1 3 5 7 99 #> [2,] 2 4 6 99 99
set_dim(1:7, c(2, 5), pad = 99, order = "C") # fills row-wise
#> [,1] [,2] [,3] [,4] [,5] #> [1,] 1 2 3 4 5 #> [2,] 6 7 99 99 99
y <- x <- 1:4 # base::dim<- fills the array column wise dim(x) <- c(2, 2) x
#> [,1] [,2] #> [1,] 1 3 #> [2,] 2 4
# dim2 will fill the array row-wise dim2(y) <- c(2, 2) y
#> [,1] [,2] #> [1,] 1 2 #> [2,] 3 4
identical(x, set_dim(1:4, c(2,2)))
#> [1] TRUE
identical(y, set_dim(1:4, c(2,2), order = "C"))
#> [1] TRUE
if (FALSE) { py_reshaped <- reticulate::array_reshape(1:4, c(2,2)) storage.mode(py_reshaped) <- "integer" # reticulate coerces to double identical(y, py_reshaped) # if needed, see listarrays:::array_reshape() for # a drop-in pure R replacement for reticulate::array_reshape() }