Home > Mobile >  Create a month.name index in r by reading dates
Create a month.name index in r by reading dates

Time:11-19

I have the following data frame called "CNO_2020_Monthly". I have only 3 months populated on this data frame.

      Var1 Freq
1 Oct 2020    4
2 Nov 2020    5
3 Dec 2020    6

I want to create a month.name index. For that, I used the code below:

CNO_2020_Monthly$MonthInd <- month.name[CNO_2020_Monthly$Var1]

The result came like that:

structure(list(Var1 = structure(1:3, .Label = c("Oct 2020", "Nov 2020", 
"Dec 2020"), class = "factor"), Freq = 4:6, MonthInd = c("January", 
"February", "March")), row.names = c(NA, -3L), class = "data.frame")

October, November, and december come as "January", "February", "March". Is that any way to create a month.name() based on the contents of the field instead of creating a sequence - meaning, that the month.name for October 2020 will be "october"?

Additional information I have additional data frames that I will merge with the one above based on the month.name - that is why I don't what to create manyally the month.name index but find a way to do it using logic.

CodePudding user response:

1) Convert Var1 to yearmon class and then format it using %B:

library(zoo)
format(as.yearmon(CNO$Var1), "%B")
## [1] "October"  "November" "December"

2) Alternately extract the month, match it to month.abb and then use that index into month.name. Note that (1) will also work in non-English locales but this one only works in English. This alternative only uses base R.

month.name[match(substr(CNO$Var1, 1, 3), month.abb)]
## [1] "October"  "November" "December"

Note

CNO <- structure(list(Var1 = structure(1:3, levels = c("Oct 2020", "Nov 2020", 
"Dec 2020"), class = "factor"), Freq = 4:6), row.names = c(NA, 
-3L), class = "data.frame")

CodePudding user response:

lubridate has a month year function my

library(lubridate)

cbind(CNO_2020_Monthly, MonthInd = format(my(CNO_2020_Monthly$Var1), "%B"))
      Var1 Freq MonthInd
1 Oct 2020    4  October
2 Nov 2020    5 November
3 Dec 2020    6 December
  • Related