首页 > 解决方案 > melt() 使用所有列名作为 id 变量

问题描述

所以,有了这个虚拟数据集

test_species <- c("a", "b", "c", "d", "e")
test_abundance <- c(4, 7, 15, 2, 9)
df <- rbind(test_species, test_abundance)
df <- as.data.frame(df)
colnames(df) <- c("a", "b", "c", "d", "e")
df <- dplyr::slice(df, 2)

我们得到一个类似这样的数据框:

a     b     c     d     e    
4     7     15    2     9 

我想把它变成类似的东西

species      abundance
a            4
b            7
c            15
d            2
e            9

使用 reshape2 函数melt()。我试过代码

melted_df <- melt(df,
              variable.name = "species", 
              value.name = "abundance")

但这告诉我:“使用 a、b、c、d、e 作为 id 变量”,最终结果如下所示:

a     b     c     d     e    
4     7     15    2     9 

我做错了什么,我该如何解决?

标签: rreshape2melt

解决方案


您可以从一开始就以正确的形状定义它,仅使用基本库函数:

> data.frame(species=test_species, abundance=test_abundance)
  species abundance
1       a         4
2       b         7
3       c        15
4       d         2
5       e         9

推荐阅读