A C
A C

Reputation: 51

Creating a function in R to convert a unit of measurement

I would like to create a function that converts a measurement from meters to inches. The goal is to input a measurement (in meters) into the function and it will return a character in US customary units (X ft, X inches). For example, if you pass the value 1.46 to your function, the output will be the string "4 ft 9 1/2 in".

My approach to creating this function was to create a function where it would convert the input from meters to inches, and then create another function where it calculates the remainder, concatenate those 2 numbers into a vector and convert that into a string where it would be in US customary units somehow. I don't know if my logic would work here, but that's all I have so far. This is my code that I've written so far and it incorrectly returns the first number in the vector which is the feet.

convert_to_ft <- function(height) {

ft <- ((height * 39.3701) / 12)
}

remainder <- function(height) {

remain <- (((height * 39.3701) / 12) %% 12
}


convert_to_ft_inch <- function(height) {

x <- convert_to_ft(height)
y <- remainder(height)

z <- (as.numeric(x) - as.numeric(y))

result <- c(z, y)
return(result)
}

Can someone help me with how I can approach this problem? I feel like I'm tackling this at the wrong angle.

Upvotes: 1

Views: 6651

Answers (1)

Cath
Cath

Reputation: 24074

I'd go with the integer part of the first conversion (meters to feet), substract it from the total number of feet, convert the remain in inches and round it. Finally, paste both results in a string:

convert_m_fi <- function(xm){
    xm_ft <- xm * 39.3701 / 12
    xm_ft_int <- floor(xm * 39.3701 / 12)
    xm_inch <- round((xm_ft - xm_ft_int) * 12, 1)
    return(paste(xm_ft_int, "ft", xm_inch, "in"))
}

convert_m_fi(1.46)
#[1] "4 ft 9.5 in"

Upvotes: 4

Related Questions