首页 > 解决方案 > 如何使用 `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

我只能使用gatherreshape功能,怎么办?

标签: r

解决方案


使用rownames_to_columnrowid_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())

推荐阅读