Home > Software engineering >  Converting data frame's column string values to integers
Converting data frame's column string values to integers

Time:06-08

cars <- data.frame(engine_volume = c('1598 ccm','1605 ccm','1900 ccm','1598 ccm','1605 ccm','1900 ccm', '1598 ccm','1605 ccm','1900 ccm', '1598 ccm')

How to convert string values from engine.volume to integers?

CodePudding user response:

readr has a convenient function parse_number:

library(readr)
cars$engine_volume_int = parse_number(cars$engine_volume, )
cars
#    engine_volume engine_volume_int
# 1       1598 ccm              1598
# 2       1605 ccm              1605
# 3       1900 ccm              1900
# 4       1598 ccm              1598
# 5       1605 ccm              1605
# 6       1900 ccm              1900
# 7       1598 ccm              1598
# 8       1605 ccm              1605
# 9       1900 ccm              1900
# 10      1598 ccm              1598

CodePudding user response:

Use this

cars$engine_volume <-  as.integer(gsub("[a-z]" , "" , cars[[1]]))

CodePudding user response:

Another approach:

cars %>% 
  mutate(engine_volume = str_extract(engine_volume, "\\d "),
         engine_volume = as.integer(engine_volume))
  • Related