Home > Software design >  transforming number to month name in r
transforming number to month name in r

Time:07-03

there is a column of mixed factor values ['August', 'September', '1', '12', 'December']. How to transform values '1', '2' into 'January' and 'February', without hard-coding them?

CodePudding user response:

Since you're looking for a tidyverse solution, I recommend recode().

library(dplyr)
library(tibble)

month_key <- deframe(tibble(X = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
                            Y = c("January", "Febuary", "March", 
                                  "April", "May", "June", "July",
                                  "August", "September", "October", 
                                  "November", "December")))

mutate(df, month = recode(month, !!!month_key))

# # A tibble: 5 × 1
#   month  
#   <chr>  
# 1 April  
# 2 August 
# 3 January
# 4 March  
# 5 January

Data

df <- tibble(month = c("April", "August", "1", "3", "January"))

CodePudding user response:

You can try this


df$month <- ifelse(df$month %in% month.name , df$month ,
 month.name[as.numeric(df$month)])

  • Data
df <- data.frame(month = c('August', 'September', '1', '12', 'December'))
  • Output
      month
1    August
2 September
3   January
4  December
5  December

If the Warning message annoying you

df$month <- lapply(df$month , \(x) if(x %in% month.name) x else month.name[as.numeric(x)]) |> unlist()
  • Related