pluck
pluck

Reputation: 97

Extract two years from a single string

I have a table and I'm trying to manipulate it to extract year values and put it into a new field in that table. For example:

Original Table

Code    Description
A       Acme (1985 - 2002)
B       Coakc (2011 - 2012)
A       Jupiter(11) (2011 - )
C       Capital Management Corporation (2011 - )
D       Diuretics Inc (2011 - )
E       Charter (2011 - )

Desired Result

Code    Description                     Start_Year  End_Year
A       Acme                            1985        2002
B       Coakc                           2011        2012
A       Jupiter(11)                     2011    
C       Capital Management Corporation  2011    
D       Diuretics Inc                   2011       
E       Charter                         2011    

I was thinking something like:

Upvotes: 0

Views: 45

Answers (1)

Nicolas2
Nicolas2

Reputation: 2210

Using tidyverse framework you can do it the following way

library(dplyr)
library(stringr)    
df %>% mutate(Start_year=str_match(Description,"(?<=\\()\\d{4}"),
                End_year=str_match(Description,"\\d{4}(?=\\))"))

Upvotes: 3

Related Questions