I got an error and after some search I realized, that the "name of a character" causes the problem. However, I still don't understand how a character can be transferred to a function and I don't know how to solve it. The best I got is the name with extra "" - see below. (I could use other hacks like "mydim" everywhere, but that is not what I am looking for.)
So how can I make the following really work without an error?
a <- 5
special <- list(mydim = c(100L, 9L),
mydimnames = list(c("1", "2"), c("3", "4", "5")))
names(special)[[1]]
# [1] "mydim"
special[[1]]
# [1] 100 9
attr(x = a, which = names(special)[[1]]) <- special[[1]]
attributes(a)
# $hurz
# [1] "hurz"
# $mydim
# [1] 100 9
special2 <- list(dim = c(100L, 9L),
dimnames = list(c("1", "2"), c("3", "4", "5")))
names(special2)[[1]]
# [1] "dim" # ............................ of class character only!!
special2[[1]]
# [1] 100 9
# The following commands all result in the same error:
attr(x = a, which = as.character(names(special2)[[1]])) <- special2[[1]]
# Error in attr(x = a, which = names(special2)[[1]]) <- special2[[1]] :
# dims [product 900] do not match the length of object [1]
# The best I got with extra '':
attr(x = a, which = deparse(names(special2)[[1]])) <- special2[[1]]
attributes(a)
# $hurz
# [1] "hurz"
# $mydim
# [1] 100 9
# $`"dim"`
# [1] 100 9
For the error message in general see here.
It seems although "dim" is a charcater, it uses dim() and calculates 9*100 = 900...