Open Huh opened 6 years ago
I have been experimenting with S3 methods and am hoping for some feedback or suggestions on how we generally want to structure functions that use multiple classes.
In this instance I think it makes most sense to have two separate functions one for each conversion (rather than a single function that takes the temperature unit as an input).
Suggestions on the function below?
cllr_cels_to_fahr <- function(x, col = NULL) {
c2f <- function(x) {x * (9 / 5) + 32}
f <- function(x) UseMethod("f")
f.numeric <- function(x) {
assertthat::assert_that(is.numeric(x))
c2f(x)
}
f.data.frame <- function(x) {
if (is.null(col)) {
warning("Temperature column not specified. Conversion not performed!")
return(invisible(x))
}
assertthat::assert_that(is.numeric(pull(x, col)))
mutate_at(x, col, c2f)
}
f(x)
}
@foresthayes, what if you write one function that deals with converting both, then partially apply that function to create the cels_to_fahr
and fahr_to_cels
?
cllr_conv_temp <- function(x, to) {
...
}
# then
cllr_cels_to_fahr <- function(x) {
cllr_conv_temp(x, fahr)
}
# and
cllr_fahr_to_cels <- function(x) {
cllr_conv_temp(x, cels)
}
I'm still trying to figure my way around this library to help contribute. Maybe you've already done this.
It would be nice to be able to flip between Fahrenheit and Celsius