Skip to contents

Converts a matrix or array x into a tidy data frame with one row per cell, one column per dimension (using the dimension names if available), and a value column.

Usage

tidy_array(x, value_name = "x", require_dimnames = TRUE)

Arguments

x

A matrix or array. Works with 2D or higher dimensions.

value_name

Character scalar: name of the value column. Default "x".

require_dimnames

Logical; if TRUE (default), error if any dimension of x lacks names. If FALSE, fallback names like Var1, Var2, … are used.

Value

A data frame with length(x) rows, one column per dimension, and a value column named value_name.

Details

Internally uses base::as.data.frame.table() to reshape x. After reshaping, all dimension columns are passed through utils::type.convert() with as.is = TRUE, so numeric-like labels (e.g., "1", "2.5") become numeric.

Examples

m <- matrix(1:6, nrow = 2, dimnames = list(age = c("2", "3"), year = c("2001", "2002", "2003")))
tidy_array(m)
#>   age year x
#> 1   2 2001 1
#> 2   3 2001 2
#> 3   2 2002 3
#> 4   3 2002 4
#> 5   2 2003 5
#> 6   3 2003 6

a <- array(1:8,
  dim = c(2, 2, 2),
  dimnames = list(age = c("2", "3"), year = c("2001", "2002"), area = c("N", "S"))
)
tidy_array(a, value_name = "val")
#>   age year area val
#> 1   2 2001    N   1
#> 2   3 2001    N   2
#> 3   2 2002    N   3
#> 4   3 2002    N   4
#> 5   2 2001    S   5
#> 6   3 2001    S   6
#> 7   2 2002    S   7
#> 8   3 2002    S   8

# Permissive mode if dimnames are missing:
dimnames(m) <- NULL
tidy_array(m, require_dimnames = FALSE)
#>   Var1 Var2 x
#> 1    A    A 1
#> 2    B    A 2
#> 3    A    B 3
#> 4    B    B 4
#> 5    A    C 5
#> 6    B    C 6