Search code examples
runit-conversion

Convert character vector of height in inches to cm?


I am given a character vector:

tibble(H = c("6'2\"", "5'10\"", "5'5\"", "5'1\"", "5'5\"", "5'4\""))

and I want to convert it to be in cm.

Please advise how can I do this?


Solution

  • There are couple of methods to use

    1) Read with fread after pasting into a single string

    library(data.table)
    fread(paste(sub('"', "", df1$H), collapse="\n"), sep="'")[, 
                   as.matrix(.SD) %*% c(30.48, 2.54)][,1]
     #[1] 187.96 177.80 165.10 154.94 165.10 162.56
    

    2) Using gsubfn

    library(gsubfn)
    as.numeric(gsubfn("(\\d)'(\\d+)", ~ as.numeric(x) * 30.48 + 
                as.numeric(y) * 2.54, sub('"', '', df1$H)))
     #[1] 187.96 177.80 165.10 154.94 165.10 162.56
    

    3) with separate

    library(tidyverse)
    df1 %>% 
        separate(H, into = c("H1", "H2"), convert = TRUE) %>%
        transmute(H = H1 * 30.48 + H2 * 2.54)
    # A tibble: 6 x 1
    #      H
    #  <dbl>
    #1  188.
    #2  178.
    #3  165.
    #4  155.
    #5  165.
    #6  163.
    

    4) with measurements

    library(measurements)
    library(tidyverse)
    df1 %>% 
       separate(H, into = c("H1", "H2"), convert = TRUE) %>%
       transmute(H = conv_unit(H1, "ft", "cm") + conv_unit(H2, "inch", "cm"))