| acast | R Documentation |
The acast() function spreads subsets of an array margin over a new dimension.
Roughly speaking, acast() can be thought of as the "array" analogy to
data.table::dcast().
But note 2 important differences:
acast() works on arrays instead of data.tables.
acast() casts into a completely new dimension
(namely ndim(x) + 1),
instead of casting into new columns.
acast(x, ...)
## Default S3 method:
acast(x, margin, grp, fill = FALSE, fill_val, ...)
x |
an atomic or recursive array. |
... |
further arguments passed to or from methods. |
margin |
a scalar integer, specifying the margin to cast from. |
grp |
a factor, where |
fill |
Boolean. |
fill_val |
scalar of the same type of
|
For the sake of illustration, consider a matrix x and a grouping factor grp.
Let the integer scalar k represent a group in grp, such that k \in 1:nlevels(grp).
Then the code
out <- acast(x, margin = 1, grp = grp)
essentially performs the following for every group k:
copy-paste the subset x[grp == k, ] to the subset out[, , k].
Please see the examples section
to get a good idea on how this function casts an array.
An array with dimensions c(dim(x), max(tabulate(grp)).
From the casted array,
out <- acast(x, margin, grp),
one can get the original x back by using
back <- asplit(out, ndim(out)) |> bind_array(along = margin).
Note, however, the following about the back-transformed array back:
back will be ordered by grp along dimension margin;
if the levels of grp did not have equal frequencies,
then dim(back)[margin] > dim(x)[margin],
and back will have more missing values than x.
broadcast_casting
# balanced acasting ====
x <- cbind(id = rep(1:3, each = 2), grp = rep(1:2, 3), val = rnorm(6))
print(x)
grp <- as.factor(x[, 2])
levels(grp) <- c("a", "b")
margin <- 1L
acast(x, margin, grp)
# unbalanced acasting ====
x <- cbind(id = c(rep(1:3, each = 2), 1), grp = c(rep(1:2, 3), 2), val = rnorm(7))
print(x)
grp <- as.factor(x[, 2])
levels(grp) <- c("a", "b")
margin <- 1L
acast(x, margin, grp, fill = TRUE)
# unbalanced acasting with raw array ====
x <- cbind(id = c(rep(1:3, each = 2), 1), grp = c(rep(1:2, 3), 2), val = sample(1:7))
x <- as_raw(x)
print(x)
grp <- x[, 2] |> as.integer() |> as.factor()
levels(grp) <- c("a", "b")
margin <- 1L
(fill_val <- as.raw(255))
acast(x, margin, grp, fill = TRUE, fill_val = fill_val)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.