Extracting numbers from vectors of strings

前端 未结 11 1121
佛祖请我去吃肉
佛祖请我去吃肉 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:45

    Extract numbers from any string at beginning position.

    x <- gregexpr("^[0-9]+", years)  # Numbers with any number of digits
    x2 <- as.numeric(unlist(regmatches(years, x)))
    

    Extract numbers from any string INDEPENDENT of position.

    x <- gregexpr("[0-9]+", years)  # Numbers with any number of digits
    x2 <- as.numeric(unlist(regmatches(years, x)))
    

提交回复
热议问题