I have a lot of data from different sites. Therefore, I would like to rename the colnames
selecting the variable names rather than numerical position in a Matrix. Here an idea of a matrix from one site:
mdat <- matrix(c(rnorm(5,100), rnorm(5, 15), rnorm(5, 0.5), rnorm(5,0.1), rnorm(5,40)), nrow = 5, ncol = 5, byrow = F,
dimnames = list(c(2011:2015), c("Pre", "Temp", "Magnesium", "Zinc", "Hum")))
then I would like to rename only specific colnames
by name, it is "Magnesium" to "Mg", and "Zinc" to "Zn".
When I use the numerical index it works perfectly:
colnames(mdat)[3:4] <- c("Zn", "Mg")
but I want to know how to do the same by column name, since within my different matrices, these variables are in different column position. I tried it, but I get an error:
colnames(mdat)[c("Zinc", "Magnesium")] <- c("Zn", "Mg")
Error in `colnames<-`(`*tmp*`, value = c("Pre", "Temp", "Magnesium", "Zinc", :
length of 'dimnames' [2] not equal to array extent
Could you tell me some way to solve that?
Thanks