0

I have a data frame in R and I have a month column and a day column containing characters like "jan", "feb", or "mar" for months or "mon", "tue" or "wed" for days. I would like to find a way to convert both columns into integers ranging from 1 to 12 for months and 1 to 7 for days. I have tried built-in functions like month.abb but when I try using match with the column for months it just returns a list of NA. Thank you very much for your help !

Pearson
  • 3
  • 1

2 Answers2

1

A general method would be to define a factor with the levels you want, and then turn it into an integer. See reprex underneath.

This would also work for weekdays.

months <- c(
  "jan", "feb", "mar", "apr", "may", "jun", 
  "jul", "aug", "sep", "oct", "nov", "des"
  )

x <- sample(months, 10, replace = TRUE)

x
#>  [1] "sep" "oct" "mar" "jun" "oct" "mar" "apr" "aug" "jul" "sep"

as.integer(factor(x, levels = months))
#>  [1]  9 10  3  6 10  3  4  8  7  9
jpiversen
  • 3,062
  • 1
  • 8
  • 12
0

Use match:

match(c("jan", "feb", "may"), tolower(month.abb))
match(c("mon", "tue", "thur"), c("mon", "tue", "wed", "thur", "fri", "sat", "sun"))
dash2
  • 2,024
  • 6
  • 15