question:how does fct_rev work

I am learning R4DS,an example confused me,these two codes below show quite differently, I tried to make a new variable through mutate(),color1 = fct_rev(color),color1 has the same value as color has.

diamonds %>%
  ggplot(aes(x = color, y = price)) +
  geom_boxplot()
diamonds %>%
  mutate(color = fct_rev(color)) %>%
  ggplot(aes(x = color, y = price)) +
  geom_boxplot()

I read the document,but helpless

your example doesnt show a mutate to make color1, it shows you redefine color.
And your example works, in so far as when I compare the two boxplots the axis color labels are in reverse order from each other.... so is there really an issue ?

I just curious how the fct_rev works,because in the second example,after using the fct_rev,the raw data (diamonds) does not change.so why the boxplot change the sequence

the raw data will never change without an assignment on diamonds.
without a diamonds = , or diamonds <- or diamonds %<>% diamonds will not change

the pipe %>% simply passes diamonds into other functions that then give outputs, i.e. you are mutating a temporary representation that is lost after you plot it
try

diamonds2 <- diamonds %>%
  mutate(color = fct_rev(color)) 

diamonds2 %>%
  ggplot(aes(x = color, y = price)) +
  geom_boxplot()

and then look at diamonds2$color

I understand what you mean ,my question is why the boxplot shows differently,the color of any observation is not changed

library(tidyverse)
library(cowplot)

p1 <- diamonds %>%
  ggplot(aes(x = color, y = price)) +
  geom_boxplot()

p2 <- diamonds %>%
  mutate(color = fct_rev(color)) %>%
  ggplot(aes(x = color, y = price)) +
  geom_boxplot()

cowplot::plot_grid(p1,p2)

I dont understand what you mean...
In relation to this image, did you expect something more than a reversal of the ordering of the x/color axis ?

Maybe I get it,fct_rev doesnot change the raw value but change the level of it.

Maybe I get it,fct_rev doesnot change the raw value but change the level of it.

f <- factor(c("green","blue","yellow"))
fct_rev(f)
[1] green blue yellow
Levels: yellow green blue

yes, fct_rev reverse the order of the Levels of a factor.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.