Extracting numbers from vectors of strings

前端 未结 11 1380
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:05

I have string like this:

years<-c(\"20 years old\", \"1 years old\")

I would like to grep only the numeric number from this vector. Expe

11条回答
  •  难免孤独
    2020-11-22 04:41

    We can also use str_extract from stringr

    years<-c("20 years old", "1 years old")
    as.integer(stringr::str_extract(years, "\\d+"))
    #[1] 20  1
    

    If there are multiple numbers in the string and we want to extract all of them, we may use str_extract_all which unlike str_extract returns all the macthes.

    years<-c("20 years old and 21", "1 years old")
    stringr::str_extract(years, "\\d+")
    #[1] "20"  "1"
    
    stringr::str_extract_all(years, "\\d+")
    
    #[[1]]
    #[1] "20" "21"
    
    #[[2]]
    #[1] "1"
    

提交回复
热议问题