Is there a way to create a function in r which takes in the value to convert, the input weight unit and output weight unit?
converter<-fuction(value_in, unit_in, unit_out){
#some code
return value_out
}
For example i want to convert 1 kg to grams. So i would write Something like this:
if (value_in=="kg" and value_out=="grams"){
return (value/1000)
}
But how do i write this if i have like over ten weight units (for example kg, st, ls, oz etc.). Do i have to write an if else statement for every possible opportunity or is there a simpler way? I thought about the switch statement but not sure how to use two expressions here.
CodePudding user response:
We can create a function containing an index with all values corresponding to a standardized unit. I suggest we use grams as the standard unit. A Kg would correspond to a correction rate of 1000.
converter <- function(unit_in, unit_out, value){
index <- c(kg=1000, g=1)
output <- value * index[unit_in] / index[unit_out]
names(output) <- NULL
output
}
converter('kg', 'g', 5)
[1] 5000
CodePudding user response:
You can use recode()
to do the conversions:
library(dplyr)
conv_key <- c("kilogram" = 1000, "gram" = 1, "milligram" = 0.0001)
conv <- function(value, unit_in, unit_out) {
input <- value*recode(unit_in, !!!conv_key)
input/recode(unit_out, !!!conv_key)
}
conv(2, "kilogram", "gram")
# [1] 2000
CodePudding user response:
Rolling your own set and method of doing unit conversions could be fun but also time-consuming and potentially error-prone. You might consider using the units
package which can perform a wide range of unit conversions:
library(units)
some_weight <- set_units(1, kg)
some_weight
# 1 [kg]
units(some_weight) <- make_units(g)
some_weight
# 1000 [g]