Month name from a numeric value

I have a dataset, under which the column value for data and time are included 2021-12-22 16:22:31
to get the month, i ran this code

> triprawdata$date <- as.Date(triprawdata$started_at) #The defalt format is yyyy-mm-dd
>   triprawdata$month <- format(as.Date(triprawdata$date), "%m")```

The output is coming as 01,02,03 denoting the month value 
Now if i want to rename this 01,02,03 into Jan,Feb,Mar,.. what should i do ?

Here is one approach:

> num_to_month <- c("01" = "Jan", "02" = "Feb", "03" = "Mar")
> num_to_month
   01    02    03 
"Jan" "Feb" "Mar" 
> num_to_month["01"]
   01 
"Jan" 
> num_to_month["02"]
   02 
"Feb" 

Hope it helps :slightly_smiling_face:

1 Like

Other options here:

library(tidyverse)
 df <- data.frame(date=c("01/01/2021", "01/04/2021" , "01/09/2021"),
                  value=c(34, 36, 44))
 
 df$month <- as.numeric(format(as.Date(df$date, format="%d/%m/%Y"),"%m"))
 
df   %>% 
  mutate(New_month=case_when(month == 01 ~'Jan',
                                 month == 04~'Apr',
                                 month == 09~'Sep')) # In this way for other months 

 #    date      value month New_month
# 1 01/01/2021    34     1       Jan
# 2 01/04/2021    36     4       Apr
# 3 01/09/2021    44     9       Sep

1 Like

You can use lubridate: add label=T
Example: Get/set months component of a date-time — month • lubridate

2 Likes

instead of %m use %b

Sys.Date()
# dont want
format(Sys.Date(),"%m")
# want 
format(Sys.Date(),"%b")
1 Like

What is the difference between m and b ?

b gives you what you want, and m doesnt ?

it worked .Thank you :smile:

I am attaching the plot,can you check ,how to order this as per month ?
jgg

 #total trips by customer type vs month
 triprawdata_v2 %>% 
   group_by(member_casual,month) %>% 
   summarise(number_of_rides = n()
   ) %>% 
   arrange(member_casual, month)  %>% 
   ggplot(aes(x = month, y = number_of_rides, fill = member_casual)) +
   geom_col(position = "dodge")
 labs(title ="total trips by customer type vs month")

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.