0
votes

I have monthly column value in number

df <- data.frame(Month= c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "1", "2", "3"))

I want to convert this to: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec, Jan, Feb, Mar

Can anyone help me with this please?

Thanking in advance for your time

2
month.abb[as.integer(df$Month)]. The month.abb is a base R constant. One unfortunate thing is that it is not locale-aware, so non-English months are not available via the same variable ... though it is rather easy to generate your own, since all it is is a character vector, length 12.r2evans

2 Answers

0
votes

Not the most elegant or programmatic solution, but you could replace all the values with the mutate() function from the dplyr package:

library(dplyr)

df = mutate(df, Month = case_when(Month == "1" ~ "Jan",
                                  Month == "2" ~ "Feb",
                                  Month == "3" ~ "Mar",
                                  Month == "4" ~ "Apr",
                                  Month == "5" ~ "May",
                                  Month == "6" ~ "Jun",
                                  Month == "7" ~ "Jul",
                                  Month == "8" ~ "Aug",
                                  Month == "9" ~ "Sep",
                                  Month == "10" ~ "Oct",
                                  Month == "11" ~ "Nov",
                                  Month == "12" ~ "Dec")

You can find documentation for using case_when() here: https://dplyr.tidyverse.org/reference/case_when.html

An alternative programmatic solution based on the comment left by @r2evans to do this in one line using the built-in R object month.abb:

df = mutate(df, Month = month.abb[as.numeric(Month)])
0
votes

Very simple way would be to have a vector with the months. Then you can use the numbers of the months as vector indices (after coercing them to integers).

Months <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

df <- data.frame(Month= c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "1", "2", "3"))
df$Month <- Months[as.integer(df$Month)]
df
#>    Month
#> 1    Jan
#> 2    Feb
#> 3    Mar
#> 4    Apr
#> 5    May
#> 6    Jun
#> 7    Jul
#> 8    Aug
#> 9    Sep
#> 10   Oct
#> 11   Nov
#> 12   Dec
#> 13   Jan
#> 14   Feb
#> 15   Mar

The same can be done with the built-in R constant month.abb instead of creating your own Months vector.

Created on 2021-02-21 by the reprex package (v1.0.0)