user1471980 - 8 months ago 36

R Question

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. Expected output is a vector:

`c(20, 1)`

How do I go about doing this?

Answer

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))
```

Source (Stackoverflow)