r - 如何使用 `gather` 或 `reshape` 将数据框重塑为长格式并在 R 中保留行名?
问题描述
df
示例如下:
library(tidyr)
df <- data.frame(q1 = c(2, 4, 5), q2 = c(1, 6, 3), q3 = c(3, 5, 6))
# q1 q2 q3
# 1 2 1 3
# 2 4 6 5
# 3 5 3 6
gather(df)
# key value
# 1 q1 2
# 2 q1 4
# 3 q1 5
# 4 q2 1
# 5 q2 6
# 6 q2 3
# 7 q3 3
# 8 q3 5
# 9 q3 6
因为我需要在 ggplot 中使用行名fill=rowname
,所以我预期的结果如下:
# key value row
# 1 q1 2 1
# 2 q1 4 2
# 3 q1 5 3
# 4 q2 1 1
# 5 q2 6 2
# 6 q2 3 3
# 7 q3 3 1
# 8 q3 5 2
# 9 q3 6 3
我只能使用gather
和reshape
功能,怎么办?
解决方案
使用rownames_to_column
或rowid_to_column
之前gather
library(tidyverse)
df %>%
rownames_to_column(var = "row") %>%
gather(key, value, -row)
# row key value
#1 1 q1 2
#2 2 q1 4
#3 3 q1 5
#4 1 q2 1
#5 2 q2 6
#6 3 q2 3
#7 1 q3 3
#8 2 q3 5
#9 3 q3 6
或者另一种方法可能是在row_number
每列之后添加gather
gather(df) %>%
group_by(key) %>%
mutate(row = row_number())
推荐阅读
- javascript - AG Grid 中未设置多个复选框
- powershell - 使用 powershell 获取 Skype for Business 联系人状态
- java - 如何在循环中处理 CompletableFuture 线程
- r - 需要帮助优化大型网络抓取任务中的循环
- python - 将 PDF 艺术作品放置在特定位置的 Reportlab 画布上
- android - 如何在保持 Android 系统装饰的同时,获取自定义通知的整体情况?
- c# - 实体框架核心查询类型未将结果映射到对象
- python - 如何在不使用 range() python 的情况下删除文本文档的特定部分
- javascript - JavaScript:在范围内生成随机数
- algorithm - 寻找具有不可忽略的求解时间的多变量函数的最优解?