this is a simple enough question that I'm suprised I can't find any reference to anyone having asked it before. It's not the same as this, nor is it covered by this discussion.
I have a 4-d matrix (dimensions 16x10x15x39) with named dimnames (it's what happens when you cast
a dataframe from, e.g. a csv. You get to the names of the dimnames with names(dimnames(matrix))
)
I then want to replace the columns (i.e. the first dimension) with fractions of the row total, so I do this:
matrix2 <- apply(matrix1, c(2,3,4), function(x){x/sum(x)})
But now names(dimnames(matrix2))
is blank for the first dimension. The other dimname names have been preserved.
So: how can I run apply
over a matrix with named dimnames and keep the names of all the remaining dimensions?
A reproducable example
Here's simple example of the problem. Just run the whole code and look at the last two lines.
x <- data.frame(
name=c("bob","james","sarah","bob","james",
"sarah","bob","james","sarah","bob",
"james","sarah"),
year=c("1995","1995","1995","1995","1995",
"1995","2005","2005","2005","2005",
"2005","2005"),
sample_num=c("sample1","sample1","sample1",
"sample2","sample2","sample2",
"sample1","sample1","sample1",
"sample2","sample2","sample2"),
value=c(1,2,3,2,3,4,1,2,3,2,3,4)
)
x <- cast(x, sample_num ~ name ~ year)
x_fractions <- apply(y,c(2,3),function(x){x / sum(x)})
names(dimnames(x))
names(dimnames(x_fractions))