R 用第二个数据框中定义的类别替换数据框列名的公式

R 用第二个数据框中定义的类别替换数据框列名的公式,r,dataframe,names,R,Dataframe,Names,假设我有宽格式的数据(行中的样本和列中的物种) 我期待的最终结果是: Sample Crustose CCA Erect 1 23 3 3 2 18 5 52 3 16 22 11 4 12 1 30 5 32 4 22 6 42 54 22 你

假设我有宽格式的数据(行中的样本和列中的物种)

我期待的最终结果是:

Sample Crustose CCA Erect
  1       23      3     3     
  2       18      5    52    
  3       16     22    11       
  4       12      1    30       
  5       32      4    22       
  6       42     54    22 
你对如何处理这个问题有何建议?谢谢你的帮助和我已经收到的令人惊讶的建议

Re Q1)我们可以使用
match
进行名称查找:

names(species)[2:ncol(species)] <- reference$Functional_group[match(names(species), reference$Species_name)][-1]

太棒了!谢谢(也感谢对我的问题所做的编辑和更正)这样就行了,但如果我想用相同的名称对所有功能组列求和怎么办?
rowSums(species[grep(“same_name”,names(species)))
No这对我不起作用,它给出了一个全为零的行。行和(物种[grep(“相同的名称”,名称(物种)))[1]0我想要的是有一个最终的data.frame,其中包含所有功能组数据的和。我们成功地更改了名称,但我一直在用相同的名称对所有列求和。我通过转换为长格式,然后再转换为宽格式,找到了一些解决方案,但我想知道是否有更快的方法……因此在我之前的评论中,您实际上必须在colname中输入我写的“相同的名称”(例如,您写的是“Crustose”而不是“相同的名称”)。但是,一次只对一个名称有效。请参阅我上面编辑的答案,了解如何对同名列进行求和,以及如何对所有不同的列名进行求和。
names(species)[2:ncol(species)] <- reference$Functional_group[match(names(species), reference$Species_name)][-1]
Sample Crustose CCA Erect CCA Crustose
      1       21   2     3   1        2
      2       15   5    52   0        3
      3       12   1    11  22        4
      4       11   0    30   1        1
      5       32   2    22   2        0
      6       42  22    22  32        0
Sample Crustose CCA Erect
  1       23      3     3     
  2       18      5    52    
  3       16     22    11       
  4       12      1    30       
  5       32      4    22       
  6       42     54    22 
names(species)[2:ncol(species)] <- reference$Functional_group[match(names(species), reference$Species_name)][-1]
namevec <- gsub("\\.[[:digit:]]", "", names(df))
mapply(function(x) rowSums(df[which(namevec == x)]), unique(namevec))