ggplot2-solutions icon indicating copy to clipboard operation
ggplot2-solutions copied to clipboard

Exercise 9.3.3 #2 use pivot_*()

Open HossamGhorab opened this issue 3 years ago • 0 comments

https://github.com/kangnade/ggplot2-solutions/blob/e6ef9e3b271599f6e97afc0f8a3f012f276f9385/ggplot2_solutions_chapter9.Rmd#L37

The question says:

How can you convert back and forth between the economics and economics long datasets built into ggplot2?

The chapter uses spread() & gather() functions, which are now superseded. pivot_wider() & pivot_longer() replaced them. The following code does the back & forth conversion but with the pivot_*() functions:

library(tidyverse) t_back <- economics_long %>% select(-value01) %>% pivot_wider(names_from = variable, values_from = value) identical(t_back, as_tibble(economics)) # make sure conversion is well-done

t_forth <- economics %>% pivot_longer(-date, names_to = "variable", values_to = "value", values_transform = list(levels(as.factor(economics_long$variable)), ordered = T)) %>% arrange(variable) identical(t_forth, as_tibble(economics_long[,1:3])) # make sure conversion is well-done

(I have no idea how economics_long$value01 originated) Warmly

HossamGhorab avatar Oct 02 '21 17:10 HossamGhorab