所以,使用虚拟数据集
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
我做错了什么,我该如何解决?
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函数并产生预期的结果。
您可以从一开始就使用基本库函数以正确的形状定义它:
> 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