Extract month in R

145 Views Asked by At

I have a sequence of dates in R with 2 months.

Example:

2020-01-28 / 2020-01-29 / 2020-01-30 / 2020-01-31 / 2020-02-01 / 2020-02-02

I need to extract the dates with the first month, in that case, January. But, I'm not able to do this.

I already tried to use subset, but didn't work.

2

There are 2 best solutions below

0
On BEST ANSWER

You need to get a vector with the month value. Here is an example, assuming that your data are in a vector like I did :

date = c("2020-01-28","2020-01-29","2020-01-30","2020-01-31","2020-02-01","2020-02-02")
library(lubridate)
month(date) # get the month value only
# [1] 1 1 1 1 2 2
january <- date[month(date)==1] # extract only the date which are in the 1st month
january
# [1] "2020-01-28" "2020-01-29" "2020-01-30" "2020-01-31"
1
On

Maybe you can try the code below

r <- subset(v,format(as.Date(v),"%b") == "Jan")

DATA

v <- c("2020-01-28", "2020-01-29", "2020-01-30", "2020-01-31", "2020-02-01", "2020-02-02")