Convert Height from Ft (6-1) to Inches (73) in R

Viewed 1080

I am trying to convert a column of feet to inches. Usually it is simple multiplication, but I am confused on how to convert when the format is (5-10) or (6-2) for 70 and 74 inches respectively. Here is my code so far. I am trying to change combine.data$Ht

library(rvest)
library(magrittr)
library(dplyr)
library(purrr)

years <- 2010:2020

urls <- paste0(
  'https://www.pro-football-reference.com/draft/',
  years,
  '-combine.htm')

combine.data <- map(
  urls,
  ~read_html(.x) %>% 
    html_nodes(".stats_table") %>% 
    html_table() %>% 
    as.data.frame()
) %>%
  set_names(years) %>% 
  bind_rows(.id = "year") %>% 
  filter(Pos == 'CB' | Pos == "S")
2 Answers

You can split the Ht column into two separate columns feet and inches and then perform the calculation to calculate height in feet.

library(dplyr)
library(tidyr)

combine.data %>%
  separate(Ht,c('feet', 'inches'), sep = '-', convert = TRUE, remove = FALSE) %>%
  mutate(feet = 12*feet + inches) %>%
  select(-inches)

An option is to use conv_unit from measurements after converting the character column to numeric

library(measurements)
f1 <- function(x) {
        x1 <- as.numeric(sub("-.*", "", x))
        x2 <- as.numeric(sub(".*-", "", x))
        conv_unit(x1, "ft", "inch") + x2
 }
  
combine.data$Ht <- f1(combine.data$Ht)
head(combine.data$Ht)
#[1] 69 71 72 71 69 74
f1('5-11')
#[1] 71

             

Or using only base R

f1 <- function(x) {
        x1 <- as.numeric(sub("-.*", "", x))
        x2 <- as.numeric(sub(".*-", "", x))
        (x1 * 12) + x2
 }
combine.data$Ht <- f1(combine.data$Ht)
head(combine.data$Ht)
#[1] 69 71 72 71 69 74
Related