[R] extract bits of a character vector

Duncan Murdoch murdoch at stats.uwo.ca
Thu Oct 23 01:14:01 CEST 2008


On 22/10/2008 5:02 PM, jonas garcia wrote:
> Dear list:
> 
> 
> 
> I have the following problem: From a vector like this:
> 
> vec<- c("mud_1999_area_A", "gravel_2004_area_F")
> 
> 
> 
> I would like to get the year in a separate vector, such
> 
> 
> 
> y<- c("1999", "2004")
> 
> 
> 
> I´ve been looking to grep() but I'm not sure how to do this.

You want sub() or gsub().  For example, if the year is always the only 
digits in the string, then

gsub("[^[:digit:]]", "", vec)

(which says delete all non-digits).

Duncan Murdoch



More information about the R-help mailing list