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 gsub
s 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 "
".