I am facing a weird behaviour in R when trying to apply a map to a dataframe.
I have a dataframe named data
that has a column "month" with the string name of the months such as "jan", "feb", ..., "dec".
I would like to convert these strings to the corresponding month number, so for example "jun" becomes 6 as June is the 6th month of the year.
Following the advice of this post, I wrote the following mapping:
months = 1:12
names(months) = c("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec")
Here's the first few entries of data
before the mapping:
> data$month[1:20]
[1] mar oct oct mar mar aug aug aug sep sep sep sep aug sep sep sep mar oct mar apr
Levels: apr aug dec feb jan jul jun mar may nov oct sep
However, when I apply the map operation to data
, something seems to go wrong:
> months[data$month[1:20]]
aug nov nov aug aug feb feb feb dec dec dec dec feb dec dec dec aug nov aug jan
8 11 11 8 8 2 2 2 12 12 12 12 2 12 12 12 8 11 8 1
What I expected to obtain was something that started with 3 10 10 3 and not 8 11 11 8, since March is the 3rd month and October is the 10th month.
Am I missing something?
Thanks in advance for any help! :D