Reputation: 77
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
Upvotes: 1
Views: 1878
Reputation: 1173
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)])
Upvotes: 2
Reputation: 5274
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)
Upvotes: 0