1.13 dplyr - Data Manipulation

Pipes

A cartoon dog teaches a group of other dogs how to beg for treats. On a sign they are pointing at is a picture of a dog, showing step 1: drop one ear, then (|>) rotate your head for max cuteness.

Pipes are essential to working with tidyverse functions

dplyr

dplyr: Common Data Cleaning Tasks

Setting up: Read In Some Data

library(readr)
library(dplyr)
library(tidyr)

poke <- read_csv("https://bit.ly/poke-data")

# Scramble the rows - easier to see what each operation does to the data
new_row_order <- sample(
  x = 1:nrow(poke),
  size = nrow(poke), replace = F
)
1
Load the readr package for the read_csv function, and the dplyr package (for everything else we’re going to do later)
2
Read in the CSV using the short bit.ly URL (to make it easier to follow along in class)
3
Scramble the row order so that you can see what different operations do to the data, by listing out the number of rows in the data (1:nrow(poke)) and sampling without replacement from those rows (`sample(…, ))

Setting up: Read In Some Data

poke <- poke[new_row_order, ]
poke_short <- poke[, c(1, 2, 4:8, 14:16)]
head(poke_short) 
4
Rearrange rows in the shuffled order
5
Take a smaller subset of the columns to make it easier to display – exclude the image URL and some specific stats like attack, defense, sp_attack, sp_defense, and speed that are relevant for battle calculations.
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     9        906 Sprigat… <NA>    Grass   310    40 Grass …      0.4       4.1
2     1        107 Hitmonc… <NA>    Figh…   455    50 Punchi…      1.4      50.2
3     8        814 Raboot   <NA>    Fire    420    65 Rabbit…      0.6       9  
4     3        351 Castform <NA>    Norm…   420    70 Weathe…      0.3       0.8
5     5        560 Scrafty  <NA>    Dark…   488    65 Hoodlu…      1.1      30  
6     9        978 Tatsugi… Stretc… Drag…   475    68 Mimicr…      0.3       8  

Get Rows Matching A Condition

Cartoon showing three fuzzy monsters either selecting or crossing out rows of a data table. If the type of animal in the table is “otter” and the site is “bay”, a monster is drawing a purple rectangle around the row. If those conditions are not met, another monster is putting a line through the column indicating it will be excluded. Stylized text reads “dplyr::filter() - keep rows that satisfy your conditions.” [Learn more about dplyr::filter.](https://dplyr.tidyverse.org/reference/filter.html)

Filter: Get Rows Matching A Condition

  • df |> filter(...)
  • ... replaced by a logical condition involving a variable
  • keep only rows where that condition is true
poke_short |>
  filter(gen == 1) |>
  head()
1
Get rows where the pokemon are in the first generation
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     1        107 Hitmonc… <NA>    Figh…   455    50 Punchi…      1.4      50.2
2     1        116 Horsea   <NA>    Water   295    30 Dragon…      0.4       8  
3     1         88 Grimer   <NA>    Pois…   325    80 Sludge…      0.9      30  
4     1        122 Mr. Mime Galari… Ice,…   460    50 Barrie…      1.3      54.5
5     1        101 Electro… Hisuian Elec…   490    60 Ball P…      1.2      66.6
6     1         75 Graveler <NA>    Rock…   390    55 Rock P…      1       105  
poke_short |>
  filter(height_m > 2) |>
  head()
2
Get rows where the pokemon is taller than 2 meters
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     5        646 Kyurem   <NA>    Drag…   660   125 Bounda…      3        325 
2     3        321 Wailord  <NA>    Water   500   170 Float …     14.5      398 
3     1        115 Kangask… <NA>    Norm…   490   105 Parent…      2.2       80 
4     7        796 Xurkitr… <NA>    Elec…   570    83 Glowin…      3.8      100 
5     4        464 Rhyperi… <NA>    Grou…   535   115 Drill …      2.4      283.
6     2        208 Steelix  <NA>    Stee…   510    75 Iron S…      9.2      400 
poke_short |>
  filter(height_m < .5, weight_kg > 40) |>
  head()
3
Get rows where the pokemon is shorter than 0.5 meters and weighs more than 40 kg
# A tibble: 5 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     3        331 Cacnea   <NA>    Grass   335    50 Cactus…      0.4      51.3
2     3        304 Aron     <NA>    Stee…   330    50 Iron A…      0.4      60  
3     7        790 Cosmoem  <NA>    Psyc…   400    43 Protos…      0.1    1000. 
4     3        366 Clamperl <NA>    Water   345    35 Bivalv…      0.4      52.5
5     8        826 Orbeetle <NA>    Bug,…   505    60 Seven …      0.4      40.8
poke_short |>
  filter(is.na(variant)) |>
  head()
4
Get rows where variant is NA (missing)
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     9        906 Sprigat… <NA>    Grass   310    40 Grass …      0.4       4.1
2     1        107 Hitmonc… <NA>    Figh…   455    50 Punchi…      1.4      50.2
3     8        814 Raboot   <NA>    Fire    420    65 Rabbit…      0.6       9  
4     3        351 Castform <NA>    Norm…   420    70 Weathe…      0.3       0.8
5     5        560 Scrafty  <NA>    Dark…   488    65 Hoodlu…      1.1      30  
6     8        886 Drakloak <NA>    Drag…   410    68 Careta…      1.4      11  
poke_short |>
  filter(!is.na(variant)) |>
  head()
5
Get rows where variant is NOT NA
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     9        978 Tatsugi… Stretc… Drag…   475    68 Mimicr…      0.3       8  
2     3        386 Deoxys   Speed   Psyc…   600    50 DNA Po…      1.7      60.8
3     7        774 Minior   Core    Rock…   500    60 Meteor…      0.3      40  
4     3        386 Deoxys   Normal  Psyc…   600    50 DNA Po…      1.7      60.8
5     1        122 Mr. Mime Galari… Ice,…   460    50 Barrie…      1.3      54.5
6     4        479 Rotom    Heat    Elec…   520    50 Plasma…      0.3       0.3

Get (or Remove) Some of the Columns

  • Pick out columns:
    • df |> select(...)
    • ... replaced by names or indices/positions of a variable
    • keep only columns that are mentioned
    • Remove columns by putting -c(...) around columns to eliminate
poke |>
  select(1, 2, 4:8, 14:16) |>
  head()
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     9        906 Sprigat… <NA>    Grass   310    40 Grass …      0.4       4.1
2     1        107 Hitmonc… <NA>    Figh…   455    50 Punchi…      1.4      50.2
3     8        814 Raboot   <NA>    Fire    420    65 Rabbit…      0.6       9  
4     3        351 Castform <NA>    Norm…   420    70 Weathe…      0.3       0.8
5     5        560 Scrafty  <NA>    Dark…   488    65 Hoodlu…      1.1      30  
6     9        978 Tatsugi… Stretc… Drag…   475    68 Mimicr…      0.3       8  
poke |>
  select(-c(3, 9:13)) |>
  head()
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     9        906 Sprigat… <NA>    Grass   310    40 Grass …      0.4       4.1
2     1        107 Hitmonc… <NA>    Figh…   455    50 Punchi…      1.4      50.2
3     8        814 Raboot   <NA>    Fire    420    65 Rabbit…      0.6       9  
4     3        351 Castform <NA>    Norm…   420    70 Weathe…      0.3       0.8
5     5        560 Scrafty  <NA>    Dark…   488    65 Hoodlu…      1.1      30  
6     9        978 Tatsugi… Stretc… Drag…   475    68 Mimicr…      0.3       8  
poke[, c(1, 2, 4:8, 14:16)] |>
  head()
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     9        906 Sprigat… <NA>    Grass   310    40 Grass …      0.4       4.1
2     1        107 Hitmonc… <NA>    Figh…   455    50 Punchi…      1.4      50.2
3     8        814 Raboot   <NA>    Fire    420    65 Rabbit…      0.6       9  
4     3        351 Castform <NA>    Norm…   420    70 Weathe…      0.3       0.8
5     5        560 Scrafty  <NA>    Dark…   488    65 Hoodlu…      1.1      30  
6     9        978 Tatsugi… Stretc… Drag…   475    68 Mimicr…      0.3       8  

Get (or Remove) Some of the Columns

  • Pick out columns: df |> select(...)
  • Select helpers can help get the right columns
    • matches(...), e.g. matches("year") will get all variables that have “year” in the name
      • starts_with(...), ends_with(...)
    • where(is.XXX) e.g. where(is.numeric) will get all numeric variables
    • any_of(), all_of() will match variables to names stored in a vector. any_of() gets anything that matches, all_of() will error if something is not found
    • everything() gets all variables
    • last_col() gets the last column

Get (or Remove) Some of the Columns

Select Helpers

poke |>
  select(-matches("img|attack|defense|speed")) |>
  head()
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     9        906 Sprigat… <NA>    Grass   310    40 Grass …      0.4       4.1
2     1        107 Hitmonc… <NA>    Figh…   455    50 Punchi…      1.4      50.2
3     8        814 Raboot   <NA>    Fire    420    65 Rabbit…      0.6       9  
4     3        351 Castform <NA>    Norm…   420    70 Weathe…      0.3       0.8
5     5        560 Scrafty  <NA>    Dark…   488    65 Hoodlu…      1.1      30  
6     9        978 Tatsugi… Stretc… Drag…   475    68 Mimicr…      0.3       8  
battle_stats <- c("attack", "defense", "sp_attack", "sp_defense", "speed")

poke |>
  select(-any_of(battle_stats), -img_link) |>
  head()
# A tibble: 6 × 10
    gen pokedex_no name     variant type  total    hp species height_m weight_kg
  <dbl>      <dbl> <chr>    <chr>   <chr> <dbl> <dbl> <chr>      <dbl>     <dbl>
1     9        906 Sprigat… <NA>    Grass   310    40 Grass …      0.4       4.1
2     1        107 Hitmonc… <NA>    Figh…   455    50 Punchi…      1.4      50.2
3     8        814 Raboot   <NA>    Fire    420    65 Rabbit…      0.6       9  
4     3        351 Castform <NA>    Norm…   420    70 Weathe…      0.3       0.8
5     5        560 Scrafty  <NA>    Dark…   488    65 Hoodlu…      1.1      30  
6     9        978 Tatsugi… Stretc… Drag…   475    68 Mimicr…      0.3       8  
poke |>
  select(1:2, name, type, height_m:last_col()) |>
  head()
# A tibble: 6 × 6
    gen pokedex_no name       type          height_m weight_kg
  <dbl>      <dbl> <chr>      <chr>            <dbl>     <dbl>
1     9        906 Sprigatito Grass              0.4       4.1
2     1        107 Hitmonchan Fighting           1.4      50.2
3     8        814 Raboot     Fire               0.6       9  
4     3        351 Castform   Normal             0.3       0.8
5     5        560 Scrafty    Dark,Fighting      1.1      30  
6     9        978 Tatsugiri  Dragon,Water       0.3       8  
poke |>
  select(where(is.numeric)) |>
  head()
# A tibble: 6 × 11
    gen pokedex_no total    hp attack defense sp_attack sp_defense speed
  <dbl>      <dbl> <dbl> <dbl>  <dbl>   <dbl>     <dbl>      <dbl> <dbl>
1     9        906   310    40     61      54        45         45    65
2     1        107   455    50    105      79        35        110    76
3     8        814   420    65     86      60        55         60    94
4     3        351   420    70     70      70        70         70    70
5     5        560   488    65     90     115        45        115    58
6     9        978   475    68     50      60       120         95    82
# ℹ 2 more variables: height_m <dbl>, weight_kg <dbl>

Create New Variables

Cartoon of cute fuzzy monsters dressed up as different X-men characters, working together to add a new column to an existing data frame. Stylized title text reads “dplyr::mutate - add columns, keep existing.” [Learn more about dplyr::mutate.](https://dplyr.tidyverse.org/reference/mutate.html)

Create New Variables

  • df |> mutate(newvar= XXX(...))
  • XXX can be any function
  • use ‘bare’ column names (not df$variable_name – just variable_name)
  • ... provides arguments to the function
poke_short <- poke_short |>
  mutate(
    bmi = weight_kg / (height_m^2),
    weight_lbs = weight_kg * 2.204623
  )

poke_short |> select(-c(variant, species)) |>  head()
# A tibble: 6 × 10
    gen pokedex_no name    type  total    hp height_m weight_kg   bmi weight_lbs
  <dbl>      <dbl> <chr>   <chr> <dbl> <dbl>    <dbl>     <dbl> <dbl>      <dbl>
1     9        906 Spriga… Grass   310    40      0.4       4.1 25.6        9.04
2     1        107 Hitmon… Figh…   455    50      1.4      50.2 25.6      111.  
3     8        814 Raboot  Fire    420    65      0.6       9   25         19.8 
4     3        351 Castfo… Norm…   420    70      0.3       0.8  8.89       1.76
5     5        560 Scrafty Dark…   488    65      1.1      30   24.8       66.1 
6     9        978 Tatsug… Drag…   475    68      0.3       8   88.9       17.6 

Sort Rows By Variable Values

  • Arrange/sort rows by the value of one or more columns
  • desc() is a helper function used within arrange to indicate descending order
poke_short |>
  arrange(desc(bmi), desc(height_m)) |>
  select(-c(variant, species)) |>
  unique() |>
  head()
1
Arrange by BMI in descending order. Break any ties in BMI by sorting in descending order by height as a secondary variable.
2
Remove variant and species (to save room)
3
Get rid of duplicate rows (e.g. different variants of the same pokemon that have the same stats)
# A tibble: 6 × 10
    gen pokedex_no name   type  total    hp height_m weight_kg    bmi weight_lbs
  <dbl>      <dbl> <chr>  <chr> <dbl> <dbl>    <dbl>     <dbl>  <dbl>      <dbl>
1     7        790 Cosmo… Psyc…   400    43      0.1    1000.  99990      2204. 
2     7        774 Minior Rock…   500    60      0.3      40     444.       88.2
3     7        774 Minior Rock…   440    60      0.3      40     444.       88.2
4     3        304 Aron   Stee…   330    50      0.4      60     375       132. 
5     5        632 Durant Bug,…   484    58      0.3      33     367.       72.8
6     3        366 Clamp… Water   345    35      0.4      52.5   328.      116. 

Group Rows and Do Something By Group

  • Split: Group rows into sub-tables
  • Apply: Perform an operation on each sub table
  • Combine: Put resulting sub-tables back together into a single table
# A tibble: 1,526 × 5
     gen pokedex_no name        type             height_m
   <dbl>      <dbl> <chr>       <chr>               <dbl>
 1     9        906 Sprigatito  Grass                 0.4
 2     1        107 Hitmonchan  Fighting              1.4
 3     8        814 Raboot      Fire                  0.6
 4     3        351 Castform    Normal                0.3
 5     5        560 Scrafty     Dark,Fighting         1.1
 6     9        978 Tatsugiri   Dragon,Water          0.3
 7     3        386 Deoxys      Psychic               1.7
 8     7        774 Minior      Rock,Flying           0.3
 9     8        886 Drakloak    Dragon,Ghost          1.4
10     1        116 Horsea      Water                 0.4
11     6        658 Greninja    Water,Dark            1.5
12     7        762 Steenee     Grass                 0.7
13     9        991 Iron Bundle Ice,Water             0.6
14     8        850 Sizzlipede  Fire,Bug              0.7
15     3        302 Sableye     Dark,Ghost            0.5
16     3        386 Deoxys      Psychic               1.7
17     3        271 Lombre      Water,Grass           1.2
18     8        852 Clobbopus   Fighting              0.6
19     5        646 Kyurem      Dragon,Ice            3  
20     3        316 Gulpin      Poison                0.4
21     1         88 Grimer      Poison                0.9
22     4        393 Piplup      Water                 0.4
23     5        556 Maractus    Grass                 1  
24     1        122 Mr. Mime    Ice,Psychic           1.3
25     4        479 Rotom       Electric,Fire         0.3
26     5        499 Pignite     Fire,Fighting         1  
27     8        875 Eiscue      Ice                   1.4
28     3        364 Sealeo      Ice,Water             1.1
29     1        101 Electrode   Electric,Grass        1.2
30     1         75 Graveler    Rock,Ground           1  
31     1        150 Mewtwo      Psychic,Fighting      2  
32     3        321 Wailord     Water                14.5
33     1         82 Magneton    Electric,Steel        1  
34     4        392 Infernape   Fire,Fighting         1.2
35     1         50 Diglett     Ground                0.2
36     5        571 Zoroark     Dark                  1.6
37     5        507 Herdier     Normal                0.9
38     6        670 Floette     Fairy                 0.2
39     6        660 Diggersby   Normal,Ground         1  
40     2        200 Misdreavus  Ghost                 0.7
41     3        351 Castform    Ice                   0.3
42     1         76 Golem       Rock,Electric         1.4
43     3        386 Deoxys      Psychic               1.7
44     6        667 Litleo      Fire,Normal           0.6
45     9        978 Tatsugiri   Dragon,Water          0.3
46     6        676 Furfrou     Normal                1.2
47     7        743 Ribombee    Bug,Fairy             0.2
48     4        413 Wormadam    Bug,Ground            0.5
49     1        124 Jynx        Ice,Psychic           1.4
50     2        251 Celebi      Psychic,Grass         0.6
# ℹ 1,476 more rows

poke_short |> group_by(gen)

[[1]]
# A tibble: 191 × 5
# Groups:   gen [1]
     gen pokedex_no name       type             height_m
   <dbl>      <dbl> <chr>      <chr>               <dbl>
 1     1        107 Hitmonchan Fighting              1.4
 2     1        116 Horsea     Water                 0.4
 3     1         88 Grimer     Poison                0.9
 4     1        122 Mr. Mime   Ice,Psychic           1.3
 5     1        101 Electrode  Electric,Grass        1.2
 6     1         75 Graveler   Rock,Ground           1  
 7     1        150 Mewtwo     Psychic,Fighting      2  
 8     1         82 Magneton   Electric,Steel        1  
 9     1         50 Diglett    Ground                0.2
10     1         76 Golem      Rock,Electric         1.4
# ℹ 181 more rows

[[2]]
# A tibble: 107 × 5
# Groups:   gen [1]
     gen pokedex_no name       type          height_m
   <dbl>      <dbl> <chr>      <chr>            <dbl>
 1     2        200 Misdreavus Ghost              0.7
 2     2        251 Celebi     Psychic,Grass      0.6
 3     2        222 Corsola    Water,Rock         0.6
 4     2        167 Spinarak   Bug,Poison         0.5
 5     2        208 Steelix    Steel,Ground       9.2
 6     2        226 Mantine    Water,Flying       2.1
 7     2        154 Meganium   Grass              1.8
 8     2        237 Hitmontop  Fighting           1.4
 9     2        164 Noctowl    Normal,Flying      1.6
10     2        214 Heracross  Bug,Fighting       1.5
# ℹ 97 more rows

[[3]]
# A tibble: 144 × 5
# Groups:   gen [1]
     gen pokedex_no name      type          height_m
   <dbl>      <dbl> <chr>     <chr>            <dbl>
 1     3        351 Castform  Normal             0.3
 2     3        386 Deoxys    Psychic            1.7
 3     3        302 Sableye   Dark,Ghost         0.5
 4     3        271 Lombre    Water,Grass        1.2
 5     3        316 Gulpin    Poison             0.4
 6     3        364 Sealeo    Ice,Water          1.1
 7     3        321 Wailord   Water             14.5
 8     3        351 Castform  Ice                0.3
 9     3        373 Salamence Dragon,Flying      1.5
10     3        339 Barboach  Water,Ground       0.4
# ℹ 134 more rows

[[4]]
# A tibble: 116 × 5
# Groups:   gen [1]
     gen pokedex_no name      type           height_m
   <dbl>      <dbl> <chr>     <chr>             <dbl>
 1     4        393 Piplup    Water               0.4
 2     4        479 Rotom     Electric,Fire       0.3
 3     4        392 Infernape Fire,Fighting       1.2
 4     4        413 Wormadam  Bug,Ground          0.5
 5     4        413 Wormadam  Bug,Steel           0.5
 6     4        464 Rhyperior Ground,Rock         2.4
 7     4        479 Rotom     Electric,Ghost      0.3
 8     4        394 Prinplup  Water               0.8
 9     4        418 Buizel    Water               0.7
10     4        446 Munchlax  Normal              0.6
# ℹ 106 more rows

[[5]]
# A tibble: 169 × 5
# Groups:   gen [1]
     gen pokedex_no name       type          height_m
   <dbl>      <dbl> <chr>      <chr>            <dbl>
 1     5        560 Scrafty    Dark,Fighting      1.1
 2     5        646 Kyurem     Dragon,Ice         3  
 3     5        556 Maractus   Grass              1  
 4     5        499 Pignite    Fire,Fighting      1  
 5     5        571 Zoroark    Dark               1.6
 6     5        507 Herdier    Normal             0.9
 7     5        563 Cofagrigus Ghost              1.7
 8     5        619 Mienfoo    Fighting           0.9
 9     5        558 Crustle    Bug,Rock           1.4
10     5        505 Watchog    Normal             1.1
# ℹ 159 more rows

[[6]]
# A tibble: 76 × 5
# Groups:   gen [1]
     gen pokedex_no name      type          height_m
   <dbl>      <dbl> <chr>     <chr>            <dbl>
 1     6        658 Greninja  Water,Dark         1.5
 2     6        670 Floette   Fairy              0.2
 3     6        660 Diggersby Normal,Ground      1  
 4     6        667 Litleo    Fire,Normal        0.6
 5     6        676 Furfrou   Normal             1.2
 6     6        682 Spritzee  Fairy              0.2
 7     6        720 Hoopa     Psychic,Ghost      0.5
 8     6        686 Inkay     Dark,Psychic       0.4
 9     6        704 Goomy     Dragon             0.3
10     6        687 Malamar   Dark,Psychic       1.5
# ℹ 66 more rows

[[7]]
# A tibble: 95 × 5
# Groups:   gen [1]
     gen pokedex_no name      type         height_m
   <dbl>      <dbl> <chr>     <chr>           <dbl>
 1     7        774 Minior    Rock,Flying       0.3
 2     7        762 Steenee   Grass             0.7
 3     7        743 Ribombee  Bug,Fairy         0.2
 4     7        723 Dartrix   Grass,Flying      0.7
 5     7        766 Passimian Fighting          2  
 6     7        796 Xurkitree Electric          3.8
 7     7        787 Tapu Bulu Grass,Fairy       1.9
 8     7        741 Oricorio  Ghost,Flying      0.6
 9     7        725 Litten    Fire              0.4
10     7        742 Cutiefly  Bug,Fairy         0.1
# ℹ 85 more rows

[[8]]
# A tibble: 101 × 5
# Groups:   gen [1]
     gen pokedex_no name       type         height_m
   <dbl>      <dbl> <chr>      <chr>           <dbl>
 1     8        814 Raboot     Fire              0.6
 2     8        886 Drakloak   Dragon,Ghost      1.4
 3     8        850 Sizzlipede Fire,Bug          0.7
 4     8        852 Clobbopus  Fighting          0.6
 5     8        875 Eiscue     Ice               1.4
 6     8        894 Regieleki  Electric          1.2
 7     8        828 Thievul    Dark              1.2
 8     8        856 Hatenna    Psychic           0.4
 9     8        829 Gossifleur Grass             0.4
10     8        827 Nickit     Dark              0.6
# ℹ 91 more rows

[[9]]
# A tibble: 103 × 5
# Groups:   gen [1]
     gen pokedex_no name         type           height_m
   <dbl>      <dbl> <chr>        <chr>             <dbl>
 1     9        906 Sprigatito   Grass               0.4
 2     9        978 Tatsugiri    Dragon,Water        0.3
 3     9        991 Iron Bundle  Ice,Water           0.6
 4     9        944 Shroodle     Poison,Normal       0.2
 5     9        970 Glimmora     Rock,Poison         1.5
 6     9        929 Dolliv       Grass,Normal        0.6
 7     9       1004 Chi-Yu       Dark,Fire           0.4
 8     9       1006 Iron Valiant Fairy,Fighting      1.4
 9     9        961 Wugtrio      Water               1.2
10     9        933 Naclstack    Rock                0.6
# ℹ 93 more rows

poke_short |> group_by(gen) |> mutate(height_gen_rank = order(height_m))

[[1]]
# A tibble: 191 × 6
# Groups:   gen [1]
     gen pokedex_no name       type             height_m height_gen_rank
   <dbl>      <dbl> <chr>      <chr>               <dbl>           <int>
 1     1        107 Hitmonchan Fighting              1.4               9
 2     1        116 Horsea     Water                 0.4             109
 3     1         88 Grimer     Poison                0.9              38
 4     1        122 Mr. Mime   Ice,Psychic           1.3              63
 5     1        101 Electrode  Electric,Grass        1.2              68
 6     1         75 Graveler   Rock,Ground           1                93
 7     1        150 Mewtwo     Psychic,Fighting      2               102
 8     1         82 Magneton   Electric,Steel        1               112
 9     1         50 Diglett    Ground                0.2             114
10     1         76 Golem      Rock,Electric         1.4             146
# ℹ 181 more rows

[[2]]
# A tibble: 107 × 6
# Groups:   gen [1]
     gen pokedex_no name       type          height_m height_gen_rank
   <dbl>      <dbl> <chr>      <chr>            <dbl>           <int>
 1     2        200 Misdreavus Ghost              0.7              64
 2     2        251 Celebi     Psychic,Grass      0.6              14
 3     2        222 Corsola    Water,Rock         0.6              34
 4     2        167 Spinarak   Bug,Poison         0.5              41
 5     2        208 Steelix    Steel,Ground       9.2              60
 6     2        226 Mantine    Water,Flying       2.1              90
 7     2        154 Meganium   Grass              1.8              24
 8     2        237 Hitmontop  Fighting           1.4              30
 9     2        164 Noctowl    Normal,Flying      1.6              53
10     2        214 Heracross  Bug,Fighting       1.5              57
# ℹ 97 more rows

[[3]]
# A tibble: 144 × 6
# Groups:   gen [1]
     gen pokedex_no name      type          height_m height_gen_rank
   <dbl>      <dbl> <chr>     <chr>            <dbl>           <int>
 1     3        351 Castform  Normal             0.3             122
 2     3        386 Deoxys    Psychic            1.7               1
 3     3        302 Sableye   Dark,Ghost         0.5               8
 4     3        271 Lombre    Water,Grass        1.2              13
 5     3        316 Gulpin    Poison             0.4              17
 6     3        364 Sealeo    Ice,Water          1.1              18
 7     3        321 Wailord   Water             14.5              19
 8     3        351 Castform  Ice                0.3              21
 9     3        373 Salamence Dragon,Flying      1.5             124
10     3        339 Barboach  Water,Ground       0.4               5
# ℹ 134 more rows

[[4]]
# A tibble: 116 × 6
# Groups:   gen [1]
     gen pokedex_no name      type           height_m height_gen_rank
   <dbl>      <dbl> <chr>     <chr>             <dbl>           <int>
 1     4        393 Piplup    Water               0.4              23
 2     4        479 Rotom     Electric,Fire       0.3              36
 3     4        392 Infernape Fire,Fighting       1.2              70
 4     4        413 Wormadam  Bug,Ground          0.5              73
 5     4        413 Wormadam  Bug,Steel           0.5              84
 6     4        464 Rhyperior Ground,Rock         2.4               2
 7     4        479 Rotom     Electric,Ghost      0.3               7
 8     4        394 Prinplup  Water               0.8              12
 9     4        418 Buizel    Water               0.7              16
10     4        446 Munchlax  Normal              0.6              25
# ℹ 106 more rows

[[5]]
# A tibble: 169 × 6
# Groups:   gen [1]
     gen pokedex_no name       type          height_m height_gen_rank
   <dbl>      <dbl> <chr>      <chr>            <dbl>           <int>
 1     5        560 Scrafty    Dark,Fighting      1.1              76
 2     5        646 Kyurem     Dragon,Ice         3               150
 3     5        556 Maractus   Grass              1               166
 4     5        499 Pignite    Fire,Fighting      1                22
 5     5        571 Zoroark    Dark               1.6              53
 6     5        507 Herdier    Normal             0.9              59
 7     5        563 Cofagrigus Ghost              1.7              87
 8     5        619 Mienfoo    Fighting           0.9              94
 9     5        558 Crustle    Bug,Rock           1.4             103
10     5        505 Watchog    Normal             1.1             109
# ℹ 159 more rows

[[6]]
# A tibble: 76 × 6
# Groups:   gen [1]
     gen pokedex_no name      type          height_m height_gen_rank
   <dbl>      <dbl> <chr>     <chr>            <dbl>           <int>
 1     6        658 Greninja  Water,Dark         1.5              12
 2     6        670 Floette   Fairy              0.2               2
 3     6        660 Diggersby Normal,Ground      1                 6
 4     6        667 Litleo    Fire,Normal        0.6              19
 5     6        676 Furfrou   Normal             1.2              59
 6     6        682 Spritzee  Fairy              0.2               9
 7     6        720 Hoopa     Psychic,Ghost      0.5              14
 8     6        686 Inkay     Dark,Psychic       0.4              21
 9     6        704 Goomy     Dragon             0.3              66
10     6        687 Malamar   Dark,Psychic       1.5              69
# ℹ 66 more rows

[[7]]
# A tibble: 95 × 6
# Groups:   gen [1]
     gen pokedex_no name      type         height_m height_gen_rank
   <dbl>      <dbl> <chr>     <chr>           <dbl>           <int>
 1     7        774 Minior    Rock,Flying       0.3              10
 2     7        762 Steenee   Grass             0.7              42
 3     7        743 Ribombee  Bug,Fairy         0.2              87
 4     7        723 Dartrix   Grass,Flying      0.7               3
 5     7        766 Passimian Fighting          2                13
 6     7        796 Xurkitree Electric          3.8              16
 7     7        787 Tapu Bulu Grass,Fairy       1.9              17
 8     7        741 Oricorio  Ghost,Flying      0.6              33
 9     7        725 Litten    Fire              0.4              66
10     7        742 Cutiefly  Bug,Fairy         0.1               1
# ℹ 85 more rows

[[8]]
# A tibble: 101 × 6
# Groups:   gen [1]
     gen pokedex_no name       type         height_m height_gen_rank
   <dbl>      <dbl> <chr>      <chr>           <dbl>           <int>
 1     8        814 Raboot     Fire              0.6              51
 2     8        886 Drakloak   Dragon,Ghost      1.4              32
 3     8        850 Sizzlipede Fire,Bug          0.7              52
 4     8        852 Clobbopus  Fighting          0.6              87
 5     8        875 Eiscue     Ice               1.4              98
 6     8        894 Regieleki  Electric          1.2              21
 7     8        828 Thievul    Dark              1.2              31
 8     8        856 Hatenna    Psychic           0.4              35
 9     8        829 Gossifleur Grass             0.4              55
10     8        827 Nickit     Dark              0.6              56
# ℹ 91 more rows

[[9]]
# A tibble: 103 × 6
# Groups:   gen [1]
     gen pokedex_no name         type           height_m height_gen_rank
   <dbl>      <dbl> <chr>        <chr>             <dbl>           <int>
 1     9        906 Sprigatito   Grass               0.4               4
 2     9        978 Tatsugiri    Dragon,Water        0.3              39
 3     9        991 Iron Bundle  Ice,Water           0.6              40
 4     9        944 Shroodle     Poison,Normal       0.2              94
 5     9        970 Glimmora     Rock,Poison         1.5               2
 6     9        929 Dolliv       Grass,Normal        0.6              12
 7     9       1004 Chi-Yu       Dark,Fire           0.4              32
 8     9       1006 Iron Valiant Fairy,Fighting      1.4              33
 9     9        961 Wugtrio      Water               1.2              34
10     9        933 Naclstack    Rock                0.6              63
# ℹ 93 more rows
# A tibble: 1,102 × 6
     gen pokedex_no name        type             height_m height_gen_rank
   <dbl>      <dbl> <chr>       <chr>               <dbl>           <int>
 1     9        906 Sprigatito  Grass                 0.4               4
 2     1        107 Hitmonchan  Fighting              1.4               9
 3     8        814 Raboot      Fire                  0.6              51
 4     3        351 Castform    Normal                0.3             122
 5     5        560 Scrafty     Dark,Fighting         1.1              76
 6     9        978 Tatsugiri   Dragon,Water          0.3              39
 7     3        386 Deoxys      Psychic               1.7               1
 8     7        774 Minior      Rock,Flying           0.3              10
 9     8        886 Drakloak    Dragon,Ghost          1.4              32
10     1        116 Horsea      Water                 0.4             109
11     6        658 Greninja    Water,Dark            1.5              12
12     7        762 Steenee     Grass                 0.7              42
13     9        991 Iron Bundle Ice,Water             0.6              40
14     8        850 Sizzlipede  Fire,Bug              0.7              52
15     3        302 Sableye     Dark,Ghost            0.5               8
16     3        271 Lombre      Water,Grass           1.2              13
17     8        852 Clobbopus   Fighting              0.6              87
18     5        646 Kyurem      Dragon,Ice            3               150
19     3        316 Gulpin      Poison                0.4              17
20     1         88 Grimer      Poison                0.9              38
21     4        393 Piplup      Water                 0.4              23
22     5        556 Maractus    Grass                 1               166
23     1        122 Mr. Mime    Ice,Psychic           1.3              63
24     4        479 Rotom       Electric,Fire         0.3              36
25     5        499 Pignite     Fire,Fighting         1                22
26     8        875 Eiscue      Ice                   1.4              98
27     3        364 Sealeo      Ice,Water             1.1              18
28     1        101 Electrode   Electric,Grass        1.2              68
29     1         75 Graveler    Rock,Ground           1                93
30     1        150 Mewtwo      Psychic,Fighting      2               102
31     3        321 Wailord     Water                14.5              19
32     1         82 Magneton    Electric,Steel        1               112
33     4        392 Infernape   Fire,Fighting         1.2              70
34     1         50 Diglett     Ground                0.2             114
35     5        571 Zoroark     Dark                  1.6              53
36     5        507 Herdier     Normal                0.9              59
37     6        670 Floette     Fairy                 0.2               2
38     6        660 Diggersby   Normal,Ground         1                 6
39     2        200 Misdreavus  Ghost                 0.7              64
40     3        351 Castform    Ice                   0.3              21
41     1         76 Golem       Rock,Electric         1.4             146
42     6        667 Litleo      Fire,Normal           0.6              19
43     6        676 Furfrou     Normal                1.2              59
44     7        743 Ribombee    Bug,Fairy             0.2              87
45     4        413 Wormadam    Bug,Ground            0.5              73
46     1        124 Jynx        Ice,Psychic           1.4             156
47     2        251 Celebi      Psychic,Grass         0.6              14
48     5        563 Cofagrigus  Ghost                 1.7              87
49     1        115 Kangaskhan  Normal                2.2             172
50     5        619 Mienfoo     Fighting              0.9              94
# ℹ 1,052 more rows

Group Rows and Summarize

  • Group by + summarize:
    • df |> group_by(varname) |> summarize(newvar = XXX(...))
    • One row returned per group (e.g. per value of varname)
    • All non-grouping variables dropped unless defined in summarize
    • One level of grouping is removed
poke_short |>
  group_by(gen) |>
  summarize(
    n_entries = n(),
    n_species = length(unique(species)),
    hp_mean = mean(hp),
    height_m_max = max(height_m),
    weight_kg_min = min(weight_kg),
    bmi_median = median(bmi)
  )
0
Group by generation
1
Get the total number of rows in the group
2
Get the number of different species in the group
3
Calculate the average hp for all pokemon in the group
4
Calculate the maximum height for the pokemon in the group
5
Calculate the minimum weight for all pokemon in the group
6
Calculate the median BMI for all pokemon in the group
# A tibble: 9 × 7
    gen n_entries n_species hp_mean height_m_max weight_kg_min bmi_median
  <dbl>     <int>     <int>   <dbl>        <dbl>         <dbl>      <dbl>
1     1       285        95    65.3          8.8           0.1       30.7
2     2       124        79    71.0          9.2           0.5       26.4
3     3       193       120    65.8         14.5           0.8       26.2
4     4       178        95    69.4          5.4           0.3       26.3
5     5       237       136    75.8          3.3           0.3       31.2
6     6       119        56    72.9          5.8           0.1       23.9
7     7       133        72    73.2          9.2           0.1       27  
8     8       134        79    77.9         20             0.2       24.8
9     9       123        65    75.8         12             0.4       35