如何通过矩阵中的名称而不是数字索引来重命名特定的姓氏? [英] How to rename a specific colname by name in a Matrix, rather than numerical index?

查看:112
本文介绍了如何通过矩阵中的名称而不是数字索引来重命名特定的姓氏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多来自不同站点的数据.因此,我想重命名colnames,选择变量名称而不是Matrix中的数字位置.这里是一个站点矩阵的想法:

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")))

然后我只想按名称重命名特定的colnames,即从镁"到"Mg",从锌"到"Zn".

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?

谢谢

推荐答案

我们可以使用match来获取列名称中vector(c('Zinc', 'Magnesium'))元素的数字索引.使用它可以对列名称进行子集化,并替换为对应的向量(c('Zn', 'Mg')).

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')

这篇关于如何通过矩阵中的名称而不是数字索引来重命名特定的姓氏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆