Reputation: 493
I have the following data:
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))
I want to plot the data using ggplot but I want it to be in long format to do so. I would like the data to look like this:
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))
I have looked at the reshape library, particularly the melt function but I can't quite get what I want. This article https://seananderson.ca/2013/10/19/reshape/ is quite useful as well, but again the shape of the data that I'm starting with is different, so it doesn't answer my question.
Thanks
Upvotes: 0
Views: 46
Reputation: 859
Use gather() from tidyr
d1 <- d1 %>%
gather(key=year,value=value,2:4)
Results:
# 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
Upvotes: 2