'Extract Month and Day from Date in R
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
Solution 1:[1]
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
Solution 2:[2]
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'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akrun |
| Solution 2 | AndrewGB |
