【问题标题】:Converting Height Measurements from Imperial to Metric units [closed]将高度测量值从英制单位转换为公制单位
【发布时间】:2019-03-20 16:20:51
【问题描述】:

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

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

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

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

【问题讨论】:

  • Related。你只需要提取想要的值(可能使用grep
  • 那些因广泛而投票结束的人能否提出缩小范围的方法?我不清楚如何这个问题太宽泛了。

标签: r


【解决方案1】:

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

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

【讨论】:

  • 5' 3" 虽然不是 5.3 英尺...
  • 现在应该可以更新了。再次感谢您。
猜你喜欢
  • 2020-01-30
  • 2010-09-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多