Portal Data Iteration With Loops (solution)

NoteExercise

This exercise revisits some of the functions from Portal Data Iteration Without Loops, but this time you’ll use for loops to do the iteration.

If surveys.csv is not in your working directory then download it. Load it using read_csv.

The following function classifies an individual based on its weight:

classify_by_weight <- function(weight) {
  if (is.na(weight)) {
    weight_class <- "unknown"
  } else if (weight < 20) {
    weight_class <- "small"
  } else if (weight <= 50) {
    weight_class <- "medium"
  } else {
    weight_class <- "large"
  }
  return(weight_class)
}

1. Use classify_by_weight and a for loop to determine the weight class for each value in the following vector, store the weight classes in a vector, and after the loop display the vector.

weights <- c(15, 25, 35, 45, NA, 70, 72)

2. Use classify_by_weight and a for loop to determine the weight class for each individual in surveys and store the weight classes in a vector. Add this vector to surveys as a new column named weight_class and then use dplyr to count the number of individuals in each weight class.

3. The following function estimates daily energy needs based on an individual’s genus and weight:

energy_budget <- function(genus, weight) {
  if (genus == "Dipodomys") {
    energy <- 0.065 * weight ^ 0.75 * 24
  } else if (genus == "Chaetodipus") {
    energy <- 0.080 * weight ^ 0.75 * 24
  } else {
    energy <- 0.073 * weight ^ 0.75 * 24
  }
  return(energy)
}

Use energy_budget and a for loop to estimate the energy budget for each pair of values in the following vectors, store the energy budgets in a vector, and after the loop display the vector.

genera <- c("Dipodomys", "Chaetodipus", "Neotoma", "Dipodomys")
weights <- c(45, 22, 156, 38)
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: 35549 Columns: 9
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (2): species_id, sex
dbl (7): record_id, month, day, year, plot_id, hindfoot_length, weight

ℹ 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] "small"   "medium"  "medium"  "medium"  "unknown" "large"   "large"  

2

# A tibble: 4 × 2
  weight_class count
  <chr>        <int>
1 large         6093
2 medium       18586
3 small         7604
4 unknown       3266

3

[1] 27.10404 19.50376 77.33526 23.87604