R 重塑数据框

莫莱耶

我有以下数据:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章