Data Manipulation in the tidyverse

Load library

[1]:
library(tidyverse)
Registered S3 methods overwritten by 'ggplot2':
  method         from
  [.quosures     rlang
  c.quosures     rlang
  print.quosures rlang
── Attaching packages ─────────────────────────────────────── tidyverse 1.2.1 ──
 ggplot2 3.1.1      purrr   0.3.2
 tibble  2.1.2      dplyr   0.8.1
 tidyr   0.8.3      stringr 1.4.0
 readr   1.3.1      forcats 0.4.0
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
 dplyr::filter() masks stats::filter()
 dplyr::lag()    masks stats::lag()

What data sets are available?

[2]:
data()
[3]:
help(starwars)

Bssic information

[4]:
class(starwars)
  1. 'tbl_df'
  2. 'tbl'
  3. 'data.frame'
[5]:
dim(starwars)
  1. 87
  2. 13
[6]:
nrow(starwars)
87
[7]:
ncol(starwars)
13
[8]:
head(starwars, 3)
A tibble: 3 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
Luke Skywalker17277blondfair blue 19maleTatooineHumanRevenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens Snowspeeder , Imperial Speeder BikeX-wing , Imperial shuttle
C-3PO 16775NA gold yellow112NA TatooineDroidAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope
R2-D2 9632NA white, bluered 33NA Naboo DroidAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens
[9]:
tail(starwars, 3)
A tibble: 3 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
BB8 NANAnone none black NAnone NA DroidThe Force Awakens
Captain Phasma NANAunknownunknownunknownNAfemaleNA NA The Force Awakens
Padmé Amidala 16545brown light brown 46femaleNabooHumanAttack of the Clones, The Phantom Menace , Revenge of the Sith H-type Nubian yacht, Naboo star skiff , Naboo fighter
[10]:
sample_n(starwars, 3)
A tibble: 3 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
Sly Moore 17848none pale white NAfemaleUmbara NA Attack of the Clones, Revenge of the Sith
Bail Prestor Organa191NAblacktan brown 67male AlderaanHumanAttack of the Clones, Revenge of the Sith
Ben Quadinaros 16365none grey, green, yelloworangeNAmale Tund ToongThe Phantom Menace

Piping

[11]:
starwars %>% head(5) %>% tail(3)
A tibble: 3 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
R2-D2 96 32NA white, bluered 33.0NA Naboo DroidAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens
Darth Vader202136none white yellow41.9male TatooineHumanRevenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope TIE Advanced x1
Leia Organa150 49brownlight brown 19.0femaleAlderaanHumanRevenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens Imperial Speeder Bike
[12]:
starwars %>%
head(5) %>%
tail(3)
A tibble: 3 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
R2-D2 96 32NA white, bluered 33.0NA Naboo DroidAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens
Darth Vader202136none white yellow41.9male TatooineHumanRevenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope TIE Advanced x1
Leia Organa150 49brownlight brown 19.0femaleAlderaanHumanRevenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens Imperial Speeder Bike

Select

[13]:
starwars %>%
select(name, birth_year, species) %>%
head(3)
A tibble: 3 × 3
namebirth_yearspecies
<chr><dbl><chr>
Luke Skywalker 19Human
C-3PO 112Droid
R2-D2 33Droid
[14]:
starwars %>%
select(name, age=birth_year, species) %>%
head(3)
A tibble: 3 × 3
nameagespecies
<chr><dbl><chr>
Luke Skywalker 19Human
C-3PO 112Droid
R2-D2 33Droid
[15]:
starwars %>%
select(-name, -birth_year, -species) %>%
head(3)
A tibble: 3 × 10
heightmasshair_colorskin_coloreye_colorgenderhomeworldfilmsvehiclesstarships
<int><dbl><chr><chr><chr><chr><chr><list><list><list>
17277blondfair blue maleTatooineRevenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens Snowspeeder , Imperial Speeder BikeX-wing , Imperial shuttle
16775NA gold yellowNA TatooineAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope
9632NA white, bluered NA Naboo Attack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens
[16]:
starwars%>%
select(starts_with('s')) %>%
head(3)
A tibble: 3 × 3
skin_colorspeciesstarships
<chr><chr><list>
fair HumanX-wing , Imperial shuttle
gold Droid
white, blueDroid
[17]:
starwars%>%
select(matches("[aeiou]{2,}")) %>%
head(3)
A tibble: 3 × 4
heighthair_colorbirth_yearspecies
<int><chr><dbl><chr>
172blond 19Human
167NA 112Droid
96NA 33Droid

Arrange

[18]:
starwars%>%
select(name, age=birth_year, mass) %>%
arrange(age) %>%
head(3)
A tibble: 3 × 3
nameagemass
<chr><dbl><dbl>
Wicket Systri Warrick 8 20
IG-88 15140
Luke Skywalker 19 77
[19]:
starwars%>%
select(name, age=birth_year, mass) %>%
arrange(desc(age)) %>%
head(3)
A tibble: 3 × 3
nameagemass
<chr><dbl><dbl>
Yoda 896 17
Jabba Desilijic Tiure6001358
Chewbacca 200 112
[20]:
starwars%>%
select(name, age=birth_year, mass) %>%
arrange(age) %>%
head(5)
A tibble: 5 × 3
nameagemass
<chr><dbl><dbl>
Wicket Systri Warrick 8 20
IG-88 15140
Luke Skywalker 19 77
Leia Organa 19 49
Wedge Antilles 21 77
[21]:
starwars%>%
select(name, age=birth_year, mass) %>%
arrange(age, mass) %>%
head(5)
A tibble: 5 × 3
nameagemass
<chr><dbl><dbl>
Wicket Systri Warrick 8 20
IG-88 15140
Leia Organa 19 49
Luke Skywalker 19 77
Wedge Antilles 21 77
[22]:
starwars%>%
select(name, age=birth_year, mass) %>%
top_n(age, n=3)
A tibble: 3 × 3
nameagemass
<chr><dbl><dbl>
Chewbacca 200 112
Jabba Desilijic Tiure6001358
Yoda 896 17

Filter

[23]:
starwars %>%
filter(birth_year > 100)
A tibble: 5 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
C-3PO 167 75NA gold yellow112NA Tatooine Droid Attack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope
Chewbacca 228 112brownunknown blue 200male Kashyyyk Wookiee Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens AT-STMillennium Falcon, Imperial shuttle
Jabba Desilijic Tiure1751358NA green-tan, brownorange600hermaphroditeNal HuttaHutt The Phantom Menace, Return of the Jedi, A New Hope
Yoda 66 17whitegreen brown 896male NA Yoda's speciesAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back
Dooku 193 80whitefair brown 102male Serenno Human Attack of the Clones, Revenge of the Sith Flitknot speeder
[24]:
starwars %>%
filter((birth_year >= 600) | (name == 'Dooku'))
A tibble: 3 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
Jabba Desilijic Tiure1751358NA green-tan, brownorange600hermaphroditeNal HuttaHutt The Phantom Menace, Return of the Jedi, A New Hope
Yoda 66 17whitegreen brown 896male NA Yoda's speciesAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back
Dooku 193 80whitefair brown 102male Serenno Human Attack of the Clones, Revenge of the Sith Flitknot speeder
[25]:
starwars %>%
filter((birth_year >= 600) | (name == 'Dooku')) %>%
select(name, age=birth_year, homeworld)
A tibble: 3 × 3
nameagehomeworld
<chr><dbl><chr>
Jabba Desilijic Tiure600Nal Hutta
Yoda 896NA
Dooku 102Serenno
[26]:
starwars %>%
filter(birth_year > 100, gender=='male')
A tibble: 3 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
Chewbacca228112brownunknownblue 200maleKashyyykWookiee Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens AT-STMillennium Falcon, Imperial shuttle
Yoda 66 17whitegreen brown896maleNA Yoda's speciesAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back
Dooku 193 80whitefair brown102maleSerenno Human Attack of the Clones, Revenge of the Sith Flitknot speeder
[27]:
starwars %>%
filter(str_detect(homeworld, "in")) %>%
head(3)
A tibble: 3 × 13
nameheightmasshair_colorskin_coloreye_colorbirth_yeargenderhomeworldspeciesfilmsvehiclesstarships
<chr><int><dbl><chr><chr><chr><dbl><chr><chr><chr><list><list><list>
Luke Skywalker172 77blondfair blue 19.0maleTatooineHumanRevenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope , The Force Awakens Snowspeeder , Imperial Speeder BikeX-wing , Imperial shuttle
C-3PO 167 75NA gold yellow112.0NA TatooineDroidAttack of the Clones , The Phantom Menace , Revenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope
Darth Vader 202136none whiteyellow 41.9maleTatooineHumanRevenge of the Sith , Return of the Jedi , The Empire Strikes Back, A New Hope TIE Advanced x1

Mutate

[28]:
starwars%>%
select(name, age=birth_year, height, mass) %>%
head(3)
A tibble: 3 × 4
nameageheightmass
<chr><dbl><int><dbl>
Luke Skywalker 1917277
C-3PO 11216775
R2-D2 33 9632
[29]:
starwars%>%
select(name, age=birth_year, height, mass) %>%
mutate(bmi=mass/(height/100)^2, obese=bmi>30) %>%
head(3)
A tibble: 3 × 6
nameageheightmassbmiobese
<chr><dbl><int><dbl><dbl><lgl>
Luke Skywalker 191727726.02758FALSE
C-3PO 1121677526.89232FALSE
R2-D2 33 963234.72222 TRUE
[30]:
starwars%>%
select(name, age=birth_year, height, mass) %>%
transmute(bmi=mass/(height/100)^2, obese=bmi>30) %>%
head(3)
A tibble: 3 × 2
bmiobese
<dbl><lgl>
26.02758FALSE
26.89232FALSE
34.72222 TRUE
[31]:
starwars %>%
transmute_if(is_character, str_to_upper) %>%
head(3)
A tibble: 3 × 7
namehair_colorskin_coloreye_colorgenderhomeworldspecies
<chr><chr><chr><chr><chr><chr><chr>
LUKE SKYWALKERBLONDFAIR BLUE MALETATOOINEHUMAN
C-3PO NA GOLD YELLOWNA TATOOINEDROID
R2-D2 NA WHITE, BLUERED NA NABOO DROID
[32]:
starwars %>%
select_at(c("birth_year", "height", "mass")) %>%
head(3)
A tibble: 3 × 3
birth_yearheightmass
<dbl><int><dbl>
1917277
11216775
33 9632
[33]:
starwars %>%
transmute_at(c("birth_year", "height", "mass"), ~ . + 1) %>%
head(3)
A tibble: 3 × 3
birth_yearheightmass
<dbl><dbl><dbl>
2017378
11316876
34 9733

Summarize

[34]:
starwars %>%
summarize(avg_mass = mean(mass, na.rm=TRUE),
          median_age=median(birth_year, na.rm=TRUE))
A tibble: 1 × 2
avg_massmedian_age
<dbl><dbl>
97.3118652
[35]:
starwars %>%
summarize_if(is.numeric, mean, na.rm=TRUE)
A tibble: 1 × 3
heightmassbirth_year
<dbl><dbl><dbl>
174.35897.3118687.56512
[36]:
starwars %>%
summarize_if(is.numeric, list(mean, median), na.rm=TRUE)
A tibble: 1 × 6
height_fn1mass_fn1birth_year_fn1height_fn2mass_fn2birth_year_fn2
<dbl><dbl><dbl><int><dbl><dbl>
174.35897.3118687.565121807952

Group by

[37]:
starwars %>%
group_by(homeworld) %>%
summarize(avg_mass=mean(mass, na.rm=T)) %>%
head(3)
A tibble: 3 × 2
homeworldavg_mass
<chr><dbl>
NA 82
Alderaan 64
Aleen Minor15
[38]:
starwars %>%
group_by(homeworld) %>%
summarize(avg_mass=mean(mass, na.rm=T)) %>%
filter(!is.na(homeworld)) %>%
head(3)
A tibble: 3 × 2
homeworldavg_mass
<chr><dbl>
Alderaan 64
Aleen Minor15
Bespin 79
[39]:
starwars %>%
group_by(homeworld, species, gender) %>%
summarize(avg_mass=mean(mass, na.rm=T), n=n()) %>%
filter(!is.na(homeworld)) %>%
head(5)
A grouped_df: 5 × 5
homeworldspeciesgenderavg_massn
<chr><chr><chr><dbl><int>
Alderaan Human female 491
Alderaan Human male 792
Aleen MinorAleenamale 151
Bespin Human male 791
Bestine IV Human male 1101

Exercises

1. Show the name, height and mass of all Droids sorted by height from tallest to shortest.

[40]:
starwars %>%
filter(species == 'Droid') %>%
arrange(desc(height)) %>%
select(name, height, mass)
A tibble: 5 × 3
nameheightmass
<chr><int><dbl>
IG-88200140
C-3PO167 75
R5-D4 97 32
R2-D2 96 32
BB8 NA NA

2. List the name and hoemworld of all non-humans who appeared in The Empire Strikes Back.

[41]:
starwars %>%
filter(str_detect(films, 'The Empire Strikes Back'), species!='Human') %>%
select(name, homeworld)
Warning message in stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)):
“argument is not an atomic vector; coercing”
A tibble: 6 × 2
namehomeworld
<chr><chr>
C-3PO Tatooine
R2-D2 Naboo
ChewbaccaKashyyyk
Yoda NA
IG-88 NA
Bossk Trandosha

3. Which homeworld has the most humans?

[42]:
starwars %>%
filter(species == "Human") %>%
group_by(homeworld) %>%
summarize(n=n()) %>%
top_n(1)
Selecting by n
A tibble: 1 × 2
homeworldn
<chr><int>
Tatooine8

4. What species has the highest average BMI? Exclude Species with only 1 member, and ignore NAs in the calculation of the average.

[43]:
starwars %>%
mutate(bmi = mass/(height/100)^2) %>%
group_by(species) %>%
summarize(avg_bmi=mean(bmi, na.rm=T), n=n()) %>%
filter(n>1) %>%
top_n(avg_bmi, n=1)
A tibble: 1 × 3
speciesavg_bmin
<chr><dbl><int>
Droid32.656135
[ ]: