How to rename a specific colname by name in a Matr

2019-05-21 06:15发布

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

标签: r matrix rename
1条回答
够拽才男人
2楼-- · 2019-05-21 06:42

We can use match to get the numeric index of the elements of the vector (c('Zinc', 'Magnesium')) among the column names. Use that to subset the column names and replace with the corresponding vector (c('Zn', 'Mg')).

 indx <- match(c('Zinc', 'Magnesium'), colnames(mdat))
 colnames(mdat)[indx] <- c('Zn', 'Mg')
查看更多
登录 后发表回答