A more flexible and pipe-friendly version of dimnames<-
.
set_dimnames(x, nm, which_dim = NULL)
x | an array |
---|---|
nm | A list or character vector. |
which_dim | a character vector or numeric vector or |
x, with modified dimnames and or axisnames
This function is quite flexible. See examples for the complete picture.
The word "dimnames" is slightly overloaded. Most commonly it refers to
the names of entries along a particular axis (e.g., date1, date2, date3,
...), but occasionally it is also used to refer to the names of the array
axes themselves (e.g, dates, temperature, pressure, ...). To disambiguate,
in the examples 'dimnames' always refers to the first case, while 'axis
names' refers to the second. set_dimnames()
can be used to set either or both
axis names and dimnames.
x <- array(1:8, 2:4) # to set axis names, leave which_dim=NULL and pass a character vector dimnames(set_dimnames(x, c("a", "b", "c")))#> $a #> NULL #> #> $b #> NULL #> #> $c #> NULL #># to set names along a single axis, specify which_dim dimnames(set_dimnames(x, c("a", "b", "c"), 2))#> [[1]] #> NULL #> #> [[2]] #> [1] "a" "b" "c" #> #> [[3]] #> NULL #># to set an axis name and names along the axis, pass a named list dimnames(set_dimnames(x, list(axis2 = c("a", "b", "c")), 2))#> [[1]] #> NULL #> #> $axis2 #> [1] "a" "b" "c" #> #> [[3]] #> NULL #>#> [[1]] #> NULL #> #> $axis2 #> [1] "a" "b" "c" #> #> $axis3 #> [1] "1" "2" "3" "4" #># if the array already has axis names, those are used when possible nx <- set_dimnames(x, paste0("axis", 1:3)) dimnames(nx)#> $axis1 #> NULL #> #> $axis2 #> NULL #> #> $axis3 #> NULL #>#> $axis1 #> NULL #> #> $axis2 #> [1] "x" "y" "z" #> #> $axis3 #> NULL #>#> $axis1 #> NULL #> #> $axis2 #> [1] "x" "y" "z" #> #> $axis3 #> NULL #># pass NULL to drop all dimnames, or just names along a single dimension nx2 <- set_dimnames(nx, c("x", "y", "z"), which_dim = "axis2") nx2 <- set_dimnames(nx2, LETTERS[1:4], which_dim = "axis3") dimnames(nx2)#> $axis1 #> NULL #> #> $axis2 #> [1] "x" "y" "z" #> #> $axis3 #> [1] "A" "B" "C" "D" #>#> NULL#> $axis1 #> NULL #> #> [[2]] #> NULL #> #> $axis3 #> [1] "A" "B" "C" "D" #>#> $axis1 #> NULL #> #> [[2]] #> NULL #> #> [[3]] #> NULL #># to preserve an axis name and only drop the dimnames, wrap the NULL in a list() dimnames(set_dimnames(nx2, list(NULL)))#> $axis1 #> NULL #> #> $axis2 #> NULL #> #> $axis3 #> NULL #>#> $axis1 #> NULL #> #> $axis2 #> NULL #> #> $axis3 #> [1] "A" "B" "C" "D" #>#> $axis1 #> NULL #> #> $axis2 #> NULL #> #> $axis3 #> [1] "A" "B" "C" "D" #>#> $axis1 #> NULL #> #> $axis2 #> NULL #> #> $axis3 #> NULL #>#> $axis1 #> NULL #> #> $axis2 #> NULL #> #> $axis3 #> NULL #>