9

I have this dataframe called test:

structure(list(event_type = structure(c(5L, 6L, 8L, 3L, 9L, 1L, 
7L, 4L, 10L, 2L), .Label = c("BLOCK", "CHL", "FAC", "GIVE", "GOAL", 
"HIT", "MISS", "SHOT", "STOP", "TAKE"), class = "factor"), hazard_ratio = c(0.909615543020822, 
1.3191464689192, 0.979677208703559, 1.02474605962247, 1.04722377755438, 
1.07656116782136, 1.01186162453814, 1.06021078216577, 0.972520062522276, 
0.915937088175971)), row.names = c(NA, -10L), class = "data.frame")

I want to reorder event_type according to hazard_ratio, so I tried this to no avail..

test %>% 
  mutate(event_type = as.character(event_type),
         event_type = fct_reorder(event_type, hazard_ratio))

1 Answers1

6

It sure looks like both methods reorder the factor on my system:

structure(list(event_type = structure(c(5L, 6L, 8L, 3L, 9L, 1L, 
7L, 4L, 10L, 2L), .Label = c("BLOCK", "CHL", "FAC", "GIVE", "GOAL", 
"HIT", "MISS", "SHOT", "STOP", "TAKE"), class = "factor"), hazard_ratio = c(0.909615543020822, 
1.3191464689192, 0.979677208703559, 1.02474605962247, 1.04722377755438, 
1.07656116782136, 1.01186162453814, 1.06021078216577, 0.972520062522276, 
0.915937088175971)), row.names = c(NA, -10L), class = "data.frame") -> test

We'll use ggplot2 for verification since it uses factors for ordering axis things.

Original:

ggplot(test, aes(hazard_ratio, event_type)) +
  geom_segment(aes(xend=0, yend=event_type))

enter image description here

Good 'ol base R

mutate(test, event_type = reorder(event_type, hazard_ratio)) %>% 
  ggplot(aes(hazard_ratio, event_type)) +
  geom_segment(aes(xend=0, yend=event_type))

enter image description here

forcats

mutate(test, event_type = fct_reorder(event_type, hazard_ratio, .fun = identity)) %>% 
  ggplot(aes(hazard_ratio, event_type)) +
  geom_segment(aes(xend=0, yend=event_type))

enter image description here

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
  • That's so weird! When I just run the `mutate` function without plotting, R shows me a data frame that has not changed, but once I `ggplot`, it is ordered –  Nov 25 '18 at 20:07
  • 1
    It reorders the factor. Do a `str()` of the data frame or a `str()` of the column before/after and you'll see that the factor changes. It's not going to rearrange the entire data frame. That's what `arrange()` does. – hrbrmstr Nov 25 '18 at 20:08