1. Learn
  2. /
  3. Courses
  4. /
  5. Introduction to Writing Functions in R

Exercise

Converting yields to metric

The yields in the NASS corn data are also given in US units, namely bushels per acre. You'll need to write some more utility functions to convert this unit to the metric unit of kg per hectare.

Bushels historically meant a volume of 8 gallons, but in the context of grain, they are now defined as masses. This mass differs for each grain! To solve this exercise, you need to know these facts.

  1. One pound (lb) is 0.45359237 kilograms (kg).
  2. One bushel is 48 lbs of barley, 56 lbs of corn, or 60 lbs of wheat.

magrittr is loaded.

Instructions 1/4

undefined XP
  • 1

    Write a function to convert masses in lb to kg. This should take a single argument, lbs.

  • 2

    Write a function to convert masses in bushels to lbs. This should take two arguments, bushels and crop. It should define a lookup vector of scale factors for each crop (barley, corn, wheat), extract the scale factor for the crop, then multiply this by the number of bushels.

  • 3

    Write a function to convert masses in bushels to kgs. This should take two arguments, bushels and crop. It should convert the mass in bushels to lbs then to kgs.

  • 4

    Write a function to convert yields in bushels/acre to kg/ha. The arguments should be bushels_per_acre and crop. Three choices of crop should be allowed: "barley", "corn", and "wheat". It should match the crop argument, then convert bushels to kgs, then convert harmonic acres to hectares.