我有数据,在大多数情况下,以厘米为单位报告高度,但偶尔以英寸和英尺为单位报告值(由于不同的站点等(。因此,例如,数据可能如下所示:
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
只要你所有的脚值都有'
,我们可以用它来找到它们,用.
代替它,然后进行转换:cm = inches * 2.54
。
举个例子:
5' 3 -> 5.3 -> [(5*12) + 3] * 2.54 = 160.02