Reputation: 10021
Given an csv file as follows, which I read by df <- read_csv('./data.csv')
:
How could I convert (or create a new column) Month
column from type string
to numeric
, such as 9
for September
, 10
for October, etc. in R?
The code below only works for abbreviation of months characters.
month <- c('Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug')
match(month, month.abb)
Out:
[1] 9 10 11 12 1 2 3 4 5 6 7 8
Upvotes: 0
Views: 485
Reputation: 11056
Another approach would be to convert the column to a factor:
Month <- factor(Month, levels=month.name)
Month
# [1] September October November December January February March April May June July August
# Levels: January February March April May June July August September October November December
as.numeric(Month)
# [1] 9 10 11 12 1 2 3 4 5 6 7 8
Upvotes: 1