Extracting numbers from vectors of strings

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

    How about

    # pattern is by finding a set of numbers in the start and capturing them
    as.numeric(gsub("([0-9]+).*$", "\\1", years))
    

    or

    # pattern is to just remove _years_old
    as.numeric(gsub(" years old", "", years))
    

    or

    # split by space, get the element in first index
    as.numeric(sapply(strsplit(years, " "), "[[", 1))
    

提交回复
热议问题