Is this a bug in R or does it make sense?
## works
aa <- matrix(nrow=1,ncol=2)
dimnames(aa)[[2]] <- c("a","b")
dimnames(aa)[[1]] <- c("c")
## does not work
bb <- matrix(nrow=1,ncol=2)
dimnames(bb)[[1]] <- c("c")
Error in dimnames(bb)[[1]] <- c("c") : 'dimnames' must be a list
Thanks for explanations !
This is expected behavior. When you assign to an index of an element of an object, R will create the element if it doesn’t exist. In your example “dimnames” doesn’t exist in
aa, so R tries to create “dimnames” based on what you’re assigning to it. Consider assigning elements named “a”, “b”, and “c” of a list:Now the problem with saying
L$a[[1]] <- anythingis thatL$adoesn’t exist yet. What happens when an element doesn’t exist is that R just creates the simplest type of element that would work. As you can see,L$a[[1]] <- 5would make sense ifL$ais a numeric vector, so R makes it a numeric vector.L$b[[3]] <- "foo"doesn’t make sense ifL$bis a numeric vector, but it would make sense ifL$bis a character vector, so that’s what R creates. ButL$c[[4]] <- c(1,2,3)can only happen ifL$cis a list, so in that case you get a list.In your case, it tries to create
dimnamesaccording to that rule; so it makesdimnames(aa)a list, but it only makesdimnames(bb)a character vector. Butdimnameshas an extra constraint that it has to be a list, so it objects and you get an error.