library(dplyr)
library(ggplot2)
# relevel factors using forcats package
library(forcats)
<- factor(c("a", "b", "c", "d"), levels = c("b", "c", "d", "a"))
f fct_relevel(f, "a", "c", "d", "b")
# relevel eye_color of starwars data
%>%
starwars mutate(eye_color = fct_relevel(eye_color, "yellow")) %>%
ggplot(aes(x = eye_color)) +
geom_bar()
UQRUG 19
meeting
2021-08-16: UQRUG 19
Participants
- Stéphane Guillou (Library): just here to help!
- Catherine Kim (Library/Biology): working on publishing code with a paper
- Jordan Pennells (ANOVA structure)
- Violeta Berdejo-Espinola (make my code more efficient)
- Omkar Ravindranatha Katagi (Here to learn R)
- … and 8 more UQRUGers!
Code snippets
Change the order of categorical variable levels (so ggplot2 uses that order instead of the alphabetical order):
Use case_when to rate or recode data:
library(dplyr)
starwarsrange(starwars$height, na.rm = TRUE)
# just based on height
<- starwars %>%
starwars_rated mutate(height_rating = case_when(height < 70 ~ "very small",
< 140 ~ "quite small",
height < 200 ~ "medium",
height TRUE ~ "tall"))
# recode based on multiple conditions
range(starwars$mass, na.rm = TRUE) # check range of mass, second vairable to recode by
<- starwars %>%
starwars_rated mutate(height_rating = case_when((height < 70) & (mass < 700)~ "very small and light",
< 140 ~ "quite small",
height < 200 ~ "medium",
height TRUE ~ "tall"))