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 !
Asked
Active
Viewed 37 times
0
-
1Post a sample of your data using `dput`. – user2974951 Feb 09 '22 at 14:00
-
How do I do that? Isn't there just a built-in R function I can use that would work all the time? – Pearson Feb 09 '22 at 14:08
-
1Check https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610. – user2974951 Feb 09 '22 at 14:12
-
`month.abb` fails because month names start with a capital letter in English. Your data doesn't. – Limey Feb 09 '22 at 14:17
2 Answers
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