Extracting numbers from vectors of strings

前端 未结 11 1371
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 04:22

    I think that substitution is an indirect way of getting to the solution. If you want to retrieve all the numbers, I recommend gregexpr:

    matches <- regmatches(years, gregexpr("[[:digit:]]+", years))
    as.numeric(unlist(matches))
    

    If you have multiple matches in a string, this will get all of them. If you're only interested in the first match, use regexpr instead of gregexpr and you can skip the unlist.

提交回复
热议问题