0

I've a data frame with the column: "Mes"... it is a numeric vector. It has 1 for January, 2 for February, and so on. But i need the names of the months.

This is my code:

What can i do to get what i need?

For example "Diciembre" is transform to: "EneroFebrero".

df$Mes <- gsub(1, "Enero", df$Mes)
df$Mes <- gsub(2, "Febrero", df$Mes)
df$Mes <- gsub(3, "Marzo", df$Mes)
df$Mes <- gsub(4, "Abril", df$Mes)
df$Mes <- gsub(5, "Mayo", df$Mes)
df$Mes <- gsub(6, "Junio", df$Mes)
df$Mes <- gsub(7, "Julio", df$Mes)
df$Mes <- gsub(8, "Agosto", df$Mes)
df$Mes <- gsub(9, "Setiembre", df$Mes)
df$Mes <- gsub(10, "Octubre", df$Mes)
df$Mes <- gsub(11, "Noviembre", df$Mes)
df$Mes <- gsub(12, "Diciembre", df$Mes)

Results:

When i apply: "unique(df$Mes)": get this:

 [1] "Enero"        "Febrero"      "Marzo"        "Abril"        "Mayo"         "Junio"       
 [7] "Julio"        "Agosto"       "Setiembre"    "Enero0"       "EneroEnero"   "EneroFebrero"
Omar Gonzales
  • 2,878
  • 7
  • 38
  • 83

1 Answers1

3

The problem is that gsub(1, ...) would match the "1" in "1", "10", "11", and "12", unless you restrict it with "^" and "$" (for example, gsub("^1$", "Enero", Mes)) or unless you go from 12 to 1 in your long list of gsub code.

An easier approach might be to use factor or basic index-based matching.

Example:

set.seed(1)
Mes <- sample(12, 20, TRUE)

index <- c("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", 
           "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre")

index[Mes]
#  [1] "Abril"     "Mayo"      "Julio"     "Noviembre" "Marzo"     "Noviembre"
#  [7] "Diciembre" "Agosto"    "Agosto"    "Enero"     "Marzo"     "Marzo"    
# [13] "Setiembre" "Mayo"      "Octubre"   "Junio"     "Setiembre" "Diciembre"
# [19] "Mayo"      "Octubre"  
factor(Mes, levels = 1:12, labels = index)
#  [1] Abril     Mayo      Julio     Noviembre Marzo     Noviembre Diciembre Agosto   
#  [9] Agosto    Enero     Marzo     Marzo     Setiembre Mayo      Octubre   Junio    
# [17] Setiembre Diciembre Mayo      Octubre  
# 12 Levels: Enero Febrero Marzo Abril Mayo Junio Julio Agosto Setiembre ... Diciembre
A5C1D2H2I1M1N2O1R2T1
  • 177,446
  • 27
  • 370
  • 450