-1

I am new to R. I have a column of heights formatted as X'X (feet and inches). I want to convert it to meters. Does anyone have any ideas?

Data:

Height
4'1 6'7 6'8 5'11 5'9 6'5 4'5 6'1 4'4 4'5 6'11 6'8 6'8 4'2 6'11 6'11 4'8 6'11 6'1 4'9 5'9 4'8 6'11 6'7 5'8 4'10 5'1 6'3 5'3 6'6 4'9 5'5 4'1 4'7 4'4 4'4

Thank you.

Erica
  • 11
  • 1
  • Please read this: https://stackoverflow.com/help/how-to-ask . Please attach some example data. Is it a homework (or something like that)? – oszkar Apr 05 '20 at 23:11
  • this question had been asked severally, refer to one of the answers: https://stackoverflow.com/questions/7214781/converting-units-in-r – linkonabe Apr 05 '20 at 23:13
  • @linkonabe, none of those answers addresses parsing the string for feet and inch components. (I'm not arguing this is not a dupe, just that those answers are just for already-`numeric` unit conversions.) – r2evans Apr 05 '20 at 23:17
  • @oskar homework. I attached the data. Thank you – Erica Apr 06 '20 at 00:00
  • Does this answer your question? [How to convert feet to cm in R?](https://stackoverflow.com/questions/59052801/how-to-convert-feet-to-cm-in-r) – saQuist Jun 07 '21 at 12:39

1 Answers1

1

Here's a quick function:

ft2m <- function(s) {
  # add inches if missing or no-quotes; adding extraneous leading zeroes is okay
  s1 <- gsub("'([0-9.]*)$", "'0\\1\"", s)
  s2 <- gsub("^([0-9.]+)\"?$", "0'\\1\"", s1)
  gre <- gregexpr("([0-9.]+)(?=')", s2, perl = TRUE)
  feet <- as.numeric(regmatches(s2, gre))
  gre <- gregexpr("(?<=')([0-9.]+)(?=\")", s2, perl = TRUE)
  inch <- as.numeric(regmatches(s2, gre))
  0.3048 * (feet + inch/12)
}

Demo:

vec <- c("5'10", "3'10\"", "0'9.3\"", "2'", "2'0", "2'0\"", "10\"")
ft2m(vec)
# [1] 1.77800 1.16840 0.23622 0.60960 0.60960 0.60960 0.25400

Explanation:

If you debug(ft2m) and look at the values of each vector post-s2, you'll see that the gsubs are making sure we have well-formatted strings.

cbind(s, s1, s2)
#      s         s1        s2       
# [1,] "5'10"    "5'010\"" "5'010\""
# [2,] "3'10\""  "3'10\""  "3'10\"" 
# [3,] "0'9.3\"" "0'9.3\"" "0'9.3\""
# [4,] "2'"      "2'0\""   "2'0\""  
# [5,] "2'0"     "2'00\""  "2'00\"" 
# [6,] "2'0\""   "2'0\""   "2'0\""  
# [7,] "10\""    "10\""    "0'10\"" 

I'm "catching" strings that are feet only, inches only, or inches without ". It does not catch non-sensical issues such as more than 12 inches. It will also allow decimal feet and inches (decimal or otherwise), which though obscure are still legal if we define this as "some number, a ', another number, and a "".

r2evans
  • 141,215
  • 6
  • 77
  • 149