-1

I've got data that, for the most part, reports height in centimeters, but with the occasional value (due to different sites, etc.) in inches and feet. So, for example, the data might look like:

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

Clearly, this is a problem for parsing the data, let alone using it. Is there a clean programatic way to convert the Imperial units into their metric counterparts within R?

I can find a number of packages like measurements that appear to be able to handle unit conversions, but nothing seems to clearly address the weird hybrid of both feet and inches.

Fomite
  • 2,213
  • 7
  • 30
  • 46
  • 1
    [Related](https://stackoverflow.com/questions/7214781/converting-units-in-r). You just need to extract wanted values (probably using `grep`) – pogibas Oct 16 '18 at 07:45
  • Can those voting to close due to broadness suggest a way to narrow the scope? It's unclear to me *how* the question is too broad. – Fomite Oct 16 '18 at 08:24

1 Answers1

1

You can also create a custom function, knowing the feet-cm conversion equation:

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

As long as all your feet values have the ', we can use that to find them, subsitute it with a ., then do the conversion: cm = inches * 2.54.

As an example:

5' 3 -> 5.3 -> [(5*12) + 3] * 2.54 = 160.02
RLave
  • 8,144
  • 3
  • 21
  • 37