Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a value in a column matching a particular pattern in R

Tags:

regex

r

I am new to R and i am not able to find how to do this.

Consider a table named Trial like this

  Col1  Col2            Col3 
   1    hey    June 24, 2013 5:15:06 PM GMT+05:30
   2    hello  april 20, 2013 5:15:06 PM GMT+05:30
   3    hey    July 23, 2012 5:15:06 PM GMT+05:30

How do i replace values of Col3 in Trial to

  Col1  Col2       Col3 
   1    hey      June 2013 
   2    hello    april 2013 
   3    hey      July 2012

ie.i need to extract only month and year and make a new column or replace in the same. Thnx in advance!

like image 281
user2786437 Avatar asked Nov 23 '25 02:11

user2786437


1 Answers

Use this for example:

 dat$Col3 <- gsub('(^\\w+).*, ([0-9]{4}).*','\\1 \\2',dat$Col3)
like image 109
agstudy Avatar answered Nov 24 '25 18:11

agstudy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!