Applies a function over the lower ranks of a tidytensor, collecting the results into a tidytensor. For example, if FUN is a function that takes a tidytensor of shape [26, 26] and returns a tidytensor of shape [13, 13], then we could apply FUN on a tidytensor of shape [3, 100, 26, 26] starting at rank 2 to get back one with shape [3, 100, 13, 13]. If flatten = TRUE, the higher ranks are collapsed to produce shape [300, 26, 26]

Ranknames are respected for both inputs and return values.

tt_apply(x, rank = 1, FUN, flatten = FALSE, drop_final_1 = TRUE, ...)

Arguments

x

the tidytensor to apply over.

rank

an indicator of the rank to apply over (see details).

FUN

the function to apply

flatten

whether to preserve the higher-rank structure, or collapse into a single rank (see description).

drop_final_1

If FUN returns a rank-0 tensor (length-1 vector), should it be collapsed? E.g. if final shape is (10, 10, 1), adjusts shape to (10, 10)

...

additional arguments passed to FUN.

Value

a new tidytensor.

Details

The rank argument should specify a single rank to apply over; if ranknames(t) <- c("sample", "rows", "cols", "channels") then rank = 2, rank = "rows", and rank = c(FALSE, TRUE, FALSE, FALSE) all indicate that FUN will be called on tidytensors with ranknames c("rows", "cols", "channels").

See also

Examples

# shape [20, 26, 26]
t <- as.tidytensor(array(rnorm(20 * 26 * 26), dim = c(20, 26, 26)))
ranknames(t) <- c("sample", "row", "col")
print(t)
#> # Rank 3 tensor, shape: (20, 26, 26), ranknames: sample, row, col
#> |  # Rank 2 tensor, shape: (26, 26)
#> |       -0.762    1.46    1.3    1.5    -1.25    -0.736  ... 
#> |       -0.977  -0.488   1.91   0.23  0.00691    -0.668  ... 
#> |         -1.1   0.424  -1.31  0.306   -0.233    -0.418  ... 
#> |      -0.0627    1.22  -2.08  0.437     1.46      1.25  ... 
#> |        -2.31    0.93  -1.07  0.812   -0.261  -0.00855  ... 
#> |       -0.348   0.186  -0.74   1.56     0.66      1.06  ... 
#> |          ...     ...    ...    ...      ...       ...  ... 
#> |  # ...

# compute the deviation from median for each sample
dev_median <- function(t) {
  return(t - median(t))
}

median_deviations <- tt_apply(t, sample, dev_median)
print(median_deviations)
#> # Rank 3 tensor, shape: (20, 26, 26), ranknames: sample, row, col
#> |  # Rank 2 tensor, shape: (26, 26)
#> |       -0.794    1.43    1.27   1.47    -1.28   -0.767  ... 
#> |        -1.01  -0.519    1.88  0.199  -0.0243   -0.699  ... 
#> |        -1.13   0.393   -1.34  0.274   -0.264    -0.45  ... 
#> |      -0.0938    1.19   -2.11  0.405     1.43     1.22  ... 
#> |        -2.34   0.899    -1.1   0.78   -0.292  -0.0397  ... 
#> |       -0.379   0.155  -0.772   1.53    0.629     1.03  ... 
#> |          ...     ...     ...    ...      ...      ...  ... 
#> |  # ...