r - 将高度测量值从英制单位转换为公制单位
问题描述
我有数据,在大多数情况下,以厘米为单位报告高度,但偶尔会以英寸和英尺为单位报告(由于不同的站点等)。因此,例如,数据可能如下所示:
Height
162
148
153
5' 3"
147
6' 0"
182
显然,这是解析数据的问题,更不用说使用它了。是否有一种干净的编程方式将英制单位转换为 R 中的公制单位?
我可以找到许多类似的软件包measurements
似乎能够处理单位转换,但似乎没有什么能清楚地解决英尺和英寸的奇怪混合。
解决方案
您还可以创建自定义函数,知道英尺-厘米转换方程:
height <- c(162,148,153,"5' 3",147,"6' 0",182)
#[1] "162" "148" "153" "5' 3" "147" "6' 0" "182"
my_conversion <- function(x, costant = 2.54) {
find_feet <- !is.na(str_match(x, "'")) # we find which values are not in cm
x[find_feet] <- gsub(" ", "", gsub("'", ".", x[find_feet])) #subsitute ' with . - and remove white spaces
x <- as.numeric(x)
feet <- floor(x[find_feet]) # feet
inch <- (x[find_feet] - feet) * 10 # inches
x[find_feet] <- ((feet * 12) + inch) * costant # here we do the conversion feet-cm
x
}
my_conversion(height)
#[1] 162.00 148.00 153.00 160.02 147.00 182.88 182.00
只要你所有的 feet 值都有'
,我们就可以用它来找到它们,用 替换它.
,然后进行转换:cm = inches * 2.54
。
举个例子:
5' 3 -> 5.3 -> [(5*12) + 3] * 2.54 = 160.02
推荐阅读
- python - Python度量ROC曲线:直方图的负预测值?
- c# - 来自 URL 的 C# XML - 根级别的数据无效。第 1 行,位置 1
- javascript - Formik & Yup 使用 yup 对数组进行表单验证
- c - 编写一个程序,按升序打印前 n 个自然数
- javascript - 有没有办法在我的 Navigator.js 文件中访问 AsyncStorage 中的数据?
- ios - iOS Swift 5 UICollectionView NIB 注册不工作,我使用 XIB 文件
- excel - 将自由文本添加到 Excel 电子表格
- amazon-web-services - 各种 AWS EC2 实例在 AWS S3 存储桶中使用相同的库文件是一种好习惯吗?
- java - How do you find the exact meaning of a word using java?
- vue.js - Getting vue to show only class with a specific value in Vue