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)
Related Topics
How to Add Row and Column to a Dataframe of Different Length
Remove Last N Rows in Data Frame With the Arbitrary Number of Rows
Duplicate Columns in Spark Dataframe
Minimum (Or Maximum) Value of Each Row Across Multiple Columns
Use Dynamic Name For New Column/Variable in 'Dplyr'
How to Get a Contingency Table
Complete Dataframe With Missing Combinations of Values
Reorder Levels of a Factor Without Changing Order of Values
If Else Statements to Check If a String Contains a Substring in R
How to Convert a Data Frame Column to Numeric Type
Add Legend to Geom_Line() Graph in R
How to Generate the First N Terms in the Series:
Drop Unused Factor Levels in a Subsetted Data Frame
How to Use a Variable to Specify Column Name in Ggplot