Reputation: 1800
How do you label dimensions in an R array? (note: I don't mean "how do you label each point on the axis within each dimension!). For example, suppose I create the following matrix:
foo <- array(NA, dim = c(2, 2, 2), dimnames = list(c(1, 2), c(3, 4), c(5, 6)))
I would like the first dimension to be labelled "foo," the second dimension to be labelled "bar," and the third dimension to be labelled "baz" so that the user of foo
can immediately see what each dimension represents.
A workaround I am aware of is to return data as a dataframe, using column names to label the various dimensions. For various reasons though, I would prefer to keep the data as denormalized (is that the right direction?) as possible.
Thanks!
Upvotes: 0
Views: 407
Reputation: 34703
I would do the following:
dims = dim(foo)
dim_names = c("foo", "bar", "baz")
dimnames(foo) =
lapply(seq_along(dims),
function(ii)
paste0(dim_names[ii], seq(to = cumsum(dims)[ii],
length.out = dims[ii])))
foo
# , , baz5
#
# bar3 bar4
# foo1 NA NA
# foo2 NA NA
#
# , , baz6
#
# bar3 bar4
# foo1 NA NA
# foo2 NA NA
Upvotes: 1