-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrange-vs-factor.R
72 lines (58 loc) · 1.81 KB
/
arrange-vs-factor.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
library(tidyverse)
library(palmerpenguins)
library(gt)
# When we make a table, our data shows up in the order it is printed.
penguins %>%
group_by(species) %>%
summarize(mean_weight = mean(body_mass_g, na.rm = TRUE)) %>%
ungroup()
penguins %>%
group_by(species) %>%
summarize(mean_weight = mean(body_mass_g, na.rm = TRUE)) %>%
ungroup() %>%
gt()
# If we want to reorder rows in a table, we use the arrange() function.
penguins %>%
group_by(species) %>%
summarize(mean_weight = mean(body_mass_g, na.rm = TRUE)) %>%
ungroup() %>%
arrange(desc(mean_weight)) %>%
gt()
# Let's see if arrange() works for reordering a bar chart.
# Here's the basic bar chart we want to make:
penguins %>%
group_by(species) %>%
summarize(mean_weight = mean(body_mass_g, na.rm = TRUE)) %>%
ungroup() %>%
ggplot(aes(x = species,
y = mean_weight)) +
geom_col()
# Let's add an arrange and see if it works.
penguins %>%
group_by(species) %>%
summarize(mean_weight = mean(body_mass_g, na.rm = TRUE)) %>%
ungroup() %>%
arrange(desc(mean_weight)) %>%
ggplot(aes(x = species,
y = mean_weight)) +
geom_col()
# It doesn't!
# Instead, we need to use factors.
# I'm using fct_reorder() from the forcats package.
# This function reorders one variable by the value of another variable.
penguins %>%
group_by(species) %>%
summarize(mean_weight = mean(body_mass_g, na.rm = TRUE)) %>%
ungroup() %>%
mutate(species = fct_reorder(species, desc(mean_weight))) %>%
ggplot(aes(x = species,
y = mean_weight)) +
geom_col()
# Does using factors work for tables?
penguins %>%
group_by(species) %>%
summarize(mean_weight = mean(body_mass_g, na.rm = TRUE)) %>%
ungroup() %>%
mutate(species = fct_reorder(species, desc(mean_weight))) %>%
gt()
# Nope!