R function for converting distances
The unitConverter
package you've been building can be even more versatile with a function converting distances from feet to meters and vice versa. This function could be invaluable for international collaborators, who frequently need to convert between these units.
Here you'll create a function accepting a numeric distance value, the unit of this input value, and the unit to which you want to convert. Then you'll store this function in the package directory. You'll use a conditional structure within your function for the four possible conversions: feet to meters, meters to feet, feet to feet (no change), and meters to meters (no change).
To convert feet to meters, multiply the feet value by 3.2808. To convert meters to feet, multiply the meter's value by 0.3048.
This exercise is part of the course
Developing R Packages
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define the dist_converter function
dist_converter <- function(___, ___, ___) {
# Fill in the missing parts of the if-else if-else flow
if (unit_from == ___ && unit_to == "meters") {
return(dist_value / 3.28)
} ___ (___ && ___) {
return(dist_value * 3.28)
} else if (___ == ___) {
warning("unit_from and unit_to are the same, returning dist_value")
return(dist_value)
} else {
___("This function only supports conversions between feet and meters.")
}
}
# Use dist_converter to convert 100 meters to feet
___