Converting a column of heights in ft into cm

Hey there!

I'm a beginner in the R world so please go easy on me!

I'm looking for a way to convert a column of peoples' heights (observed as 5'10, for example), into cm. I have installed a package called measurements but I'm still having trouble. My data frame of heights is saved as df.

Any help would be greatly appreciated.

Thanks
N

Can you paste a little part of your data frame using dput(head(df, 10))?

Sure :slight_smile:

dput(head(df, 10))
c("5'4", "5'9", "5'3", "5'2", "5'2", "6'0", "178", "171", "5'7",
"5'8")

Your data have mixed cm and ft, so using this answer:

library(tidyverse)
library(measurements)
a <- c("5'4", "5'9", "5'3", "5'2", "5'2", "6'0", "178", "171", "5'7",
  "5'8")

ft_inch <- function(str_ft_inch){
  elem <- as.integer(unlist(strsplit(str_ft_inch, "'")))
  inch <- elem[1]*12 + elem[2]
  return(conv_unit(inch, "inch", "cm"))
}

b <- sapply(a, ft_inch) %>% 
  as_tibble() %>% 
  mutate(inc = a,
         value = ifelse(!is.na(value), value, inc)) %>% 
  select(value)

I've got it to work!!! :smiley: Thank you so much!

Hi again!

I've been spending hours trying to figure out how to apply the function to more than one column at a time, to shorten the length of code I have. I've not managed to do it, and have to run the code three separate times. Does anyone know how I can do this?

> #HOUSEKEEPING
> library(tidyverse)
> library(measurements)
> library(ggplot2)
> library(dplyr)
> 
> head(cohort)
  gender  dob student.height height.dad height.mum bed.time wake.time
1 female 1985            164        172        155 22.30.00  06.30.00
2 female 1990            5'6       5'10        5'2 21.30.00  06.15.00
3 female 1990            165        178        165 22.00.00  07.00.00
4 female 1991            171        188        169 22.00.00  06.45.00
5 female 1991           5'10        6'0        5'6 22.00.00  07.00.00
6 female 1992            5'4        5'7        5'4 21.30.00  07.00.00
>
> #The heights are a mix of feet and cm, so I'll create a function to transform inches to cm.
> 
> ft_inch <- function(str_ft_inch){
+   elem <- as.integer(unlist(strsplit(str_ft_inch, "'")))
+   inch <- elem[1]*12 + elem[2]
+   return(conv_unit(inch, "inch", "cm"))
+ }
> 
> #Now I'll apply the function to student height.
> 
> cohort$student.height <- sapply(cohort$student.height, ft_inch) %>% 
+   as_tibble() %>% 
+   mutate(inc = cohort$student.height,
+          value = ifelse(!is.na(value), value, inc)) %>% 
+   select(value)
> 
> #Applying to dad height.
> 
> cohort$height.dad <- sapply(cohort$height.dad, ft_inch) %>% 
+   as_tibble() %>% 
+   mutate(inc = cohort$height.dad,
+          value = ifelse(!is.na(value), value, inc)) %>% 
+   select(value)
> 
> #Applying to mum height.
> 
> cohort$height.mum <- sapply(cohort$height.mum, ft_inch) %>% 
+   as_tibble() %>% 
+   mutate(inc = cohort$height.mum,
+          value = ifelse(!is.na(value), value, inc)) %>% 
+   select(value)