r - 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
我做错了什么,我该如何解决?
解决方案
您可以从一开始就以正确的形状定义它,仅使用基本库函数:
> 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
推荐阅读
- html - 为什么超链接在 asp.net gridview 的前几行中不起作用
- linux - Docker(撰写):没有 sudo 的连接被拒绝
- excel - 通过在excel中自动为单元格着色来创建一个矩形
- r - 我如何使用 R 中的给定格式从 chr 转到 dttm
- c# - 从 Zendesk 获取票证并插入 SQL
- mql4 - 具有自定义指标问题的 Metatrader 4 专家顾问
- android - 来自 firebase-android-sdk 的 JobInfoSchedulerService 因 DeadSystemException 而崩溃
- python - 映射大 DF
- android - 尝试在 recyclerview 中使用 searchview 时,所有项目都会消失?
- twilio - 是否有在 React Native 中使用 twilio-conversations 的库?