melt() 使用所有列名作为 id 变量

melt() is using all column names as id variables

因此,使用虚拟数据集

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

但这告诉我:"Using a, b, c, d, e as id variables",最终结果如下所示:

a     b     c     d     e    
4     7     15    2     9 

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

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

> 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

我认为 Rbind 添加了一些奇怪的行为,我无法解释原因。

一个相当基本的修复是:

test_species <-c("a", "b", "c", "d", "e")
test_abundance <- c(4, 7, 15, 2, 9)
df <- data.frame(test_species, test_abundance) #skip rbind and go straight to df
colnames(df) <- c('species', 'abundance') #colnames correct

这会跳过 rbind 函数并会给出所需的结果。