在R中创建函数以转换度量单位 [英] Creating a function in R to convert a unit of measurement

查看:53
本文介绍了在R中创建函数以转换度量单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个将度量单位从米转换为英寸的函数.目的是将一个度量(以米为单位)输入到该函数中,它将以美国惯用单位(X英尺,X英寸)返回一个字符.例如,如果将值 1.46 传递给函数,则输出将为字符串"4 ft 9 1/2 in" .

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.

推荐答案

我将使用第一次转换的 integer 部分(米至英尺),从英尺总数中减去它,将余数转换为英寸并四舍五入.最后,将两个结果粘贴到字符串中:

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"

这篇关于在R中创建函数以转换度量单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆