I have a data set where some observations are in cm and some are in inches. I need to convert all of the values to inches. The number is in one column and the unit is in another.
height unit
12.0 in
15.0 in
45.0 cm
13.0 in
52.0 cm
61.0 cm
and basically I just want all of them in inches. Should I use some kind of if statement, or subset the data where the unit is cm? Thanks for any help.
CodePudding user response:
In R base 1:
> dat$height[dat$unit=="cm"] <- dat$height[dat$unit=="cm"]*0.393701
> dat$unit <- "in"
> dat
height unit
1 12.00000 in
2 15.00000 in
3 17.71654 in
4 13.00000 in
5 20.47245 in
6 24.01576 in
R Base 2:
dat$height <- with(dat, ifelse(unit == "cm", height * 0.393701, height))
More readable with dplyr:
library(dplyr)
dat <- dat %>%
mutate(height = if_else(unit == "cm", height * 0.393701, height))
CodePudding user response:
dt <- data.table(
height = c(12.0, 15.0, 45.0, 13.0, 52.0, 61.0),
unit = c("in", "in", "cm", "in", "cm", "cm")
)
dt[, height_in_inches := ifelse(unit == "cm", height / 2.54, height)]
dt
# height unit height_in_inches
# 1: 12 in 12.000
# 2: 15 in 15.000
# 3: 45 cm 17.717
# 4: 13 in 13.000
# 5: 52 cm 20.472
# 6: 61 cm 24.016