Skip to main content

Loops size estimates by name loop (solution)

NoteExercise

If dinosaur_lengths.csv is not already in your working directory download a copy of the data on dinosaur lengths with species names. Load it into R.

The following function estimates a dinosaur’s mass based on its length and name of its taxonomic group:

get_mass_from_length_by_name <- function(length, name){
  if (name == "Stegosauria"){
    mass = 10.95 * length ^ 2.64
  }
  else if (name == "Theropoda"){
    mass = 0.73 * length ^ 3.63
  }
  else if (name == "Sauropoda"){
    mass = 214.44 * length ^ 1.46
  }
  else {
    mass = NA
  }
  return(mass)
}

Update this function so that instead of returning NA when none of the species names matches it returns mass = 25.37 * length ^ 2.49 instead.

  1. Use this function and a for loop to calculate the estimated mass for each dinosaur in dinosaur_lengths, store the masses in a vector, and after all of the calculations are complete show the first few items in the vector using head().
  2. Add the results in the vector back to the original data frame and display the new data frame.
  3. Calculate the mean mass for each species using dplyr, using the data from you created in (2).
  4. Use ggplot2 to make a histogram of the masses from (2) with a separate subplot for each species (using facet_wrap()).
CautionOutput solution

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
Rows: 500 Columns: 2
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (1): species
dbl (1): lengths

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

1

[1] 24341.68 27017.90 67453.38 22114.19 53884.76 52026.34

2

# A tibble: 500 × 3
   species      lengths masses
   <chr>          <dbl>  <dbl>
 1 Stegosauria     18.5 24342.
 2 Ankylosauria    16.4 27018.
 3 Ankylosauria    23.7 67453.
 4 Sauropoda       23.9 22114.
 5 Ankylosauria    21.7 53885.
 6 Ankylosauria    21.4 52026.
 7 Theropoda       22.3 57349.
 8 Theropoda       15.2 14160.
 9 Theropoda       21.4 49678.
10 Stegosauria     22.8 42106.
# ℹ 490 more rows

3

# A tibble: 4 × 2
  species      avg_mass
  <chr>           <dbl>
1 Ankylosauria   46819.
2 Sauropoda      16104.
3 Stegosauria    31924.
4 Theropoda      45572.

4

`stat_bin()` using `bins = 30`. Pick better value `binwidth`.