首页 > 解决方案 > 将高度测量值从英制单位转换为公制单位

问题描述

我有数据,在大多数情况下,以厘米为单位报告高度,但偶尔会以英寸和英尺为单位报告(由于不同的站点等)。因此,例如,数据可能如下所示:

Height
162
148
153
5' 3"
147
6' 0"
182

显然,这是解析数据的问题,更不用说使用它了。是否有一种干净的编程方式将英制单位转换为 R 中的公制单位?

我可以找到许多类似的软件包measurements似乎能够处理单位转换,但似乎没有什么能清楚地解决英尺和英寸的奇怪混合。

标签: r

解决方案


您还可以创建自定义函数,知道英尺-厘米转换方程:

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

推荐阅读