Home > Software design >  Extract Month and Day from Date in R
Extract Month and Day from Date in R

Time:05-15

Is there a way to extract month and day from Date as shown below

> asd <- data.frame(a = c('2020-02-15', '2020-03-16'))
> asd
           a
1 2020-02-15
2 2020-03-16

Expected output

> asd
           a    b
1 2020-02-15   Feb-15
2 2020-03-16   Mar-16

CodePudding user response:

Convert to Date class and format it

asd <- transform(asd, b = format(as.Date(a), '%b-%d'))
asd
           a      b
1 2020-02-15 Feb-15
2 2020-03-16 Mar-16

CodePudding user response:

Here's another option using strftime:

asd$b <- strftime(asd$a, '%b-%d')

Output

           a      b
1 2020-02-15 Feb-15
2 2020-03-16 Mar-16

Or we could do the same using dplyr:

library(dplyr)

asd %>% 
  mutate(b = strftime(a, '%b-%d'))
  •  Tags:  
  • r
  • Related