﻿ Months to Integer R - ITCodar

# Months to Integer R

## Convert month names to numbers in r

You can use match() with the built-in variable month.name.

match(months, month.name)
[1] 3 4 5 6 7 8 9

Or convert your months variable to a factor and then an integer:

as.integer(factor(months, levels = month.name))

## Convert months mmm to numeric

Use match and the predefined vector month.abb:

tst <- c("Jan","Mar","Dec")
match(tst,month.abb)
[1] 1 3 12

## How do I plot months with integer values using ggplot?

You can use the inbuilt vector month.abb :

library(dplyr)
library(ggplot2)

test_df %>%
mutate(months = factor(month.abb[months], levels = month.abb)) %>%
ggplot(aes(x=months, y=totals)) +
geom_bar(stat='identity', fill='red3') +
scale_y_continuous(breaks=scales::breaks_extended(n=10)) +
ggtitle('Amount by Month') +
ylab('Amount') +
xlab('Month')

## Convert string month to numeric in R

Another approach would be to convert the column to a factor:

Month <- factor(Month, levels=month.name)
Month
# [1] September October November December January February March April May June July August
# Levels: January February March April May June July August September October November December
as.numeric(Month)
# [1] 9 10 11 12 1 2 3 4 5 6 7 8

## Convert integer data into year and month

You can convert to date and then use format :

x <- c(201901, 201912, 202004)

format(as.Date(paste(x, '01'), '%Y%m%d'), '%b-%Y')
#[1] "Jan-2019" "Dec-2019" "Apr-2020"
format(as.Date(paste(x, '01'), '%Y%m%d'), '%Y-%m')
#[1] "2019-01" "2019-12" "2020-04"

You can also use zoo's yearmon :

zoo::as.yearmon(as.character(x), '%Y%m')

Using regex we can capture 4 and 2 characters and insert a "-" in between.

sub('(.{4})(.{2})', '\\1-\\2', x)

## Convert month's number to Month name

We can just use month.name to change the index of months to its corresponding name

month.name[v1]

and there is also a 3 character abbreviation for month

month.abb[v1]

### data

set.seed(24)
v1 <- sample(1:12, 24, replace = TRUE)