R重塑数据框

R reshape dataframe

我有以下数据:

library(dplyr)
library(reshape)

d1 <- data_frame(
type = c("type1", "type2", "all"),
 `2018` = c(2, 3, 5),
 `2019` = c(4, 8, 12),
 `2020` = c(2, 6, 8))

我想使用 ggplot 绘制数据,但我希望它是长格式的。我希望数据看起来像这样:

d2 <- data_frame(
  type = c("type1", "type2", "all", "type1", "type2", "all", "type1", 
"type2", "all"),
  Year = c("2018", "2018", "2018", "2019", "2019", "2019", "2020", "2020", 
"2020" ),
  Value = c(2, 3, 5, 4, 8, 12, 2, 6, 8))

我查看了 reshape 库,尤其是 melt 函数,但我不太明白我想要什么。这篇文章 https://seananderson.ca/2013/10/19/reshape/ 也很有用,但我开始使用的数据的形状又是不同的,所以它没有回答我的问题。

谢谢

使用来自 tidyr

的 gather()
d1 <- d1 %>%
  gather(key=year,value=value,2:4)

结果:

# A tibble: 9 x 3
  type  year  value
  <chr> <chr> <dbl>
1 type1 2018      2
2 type2 2018      3
3 all   2018      5
4 type1 2019      4
5 type2 2019      8
6 all   2019     12
7 type1 2020      2
8 type2 2020      6
9 all   2020      8