I have python code that converts the months in a column to numbers and names a new column
df['arrival_date_month_number'] = df['arrival_date_month'].replace(['January', 'February', 'March', 'April', 'May', 'June', 'July','August','September', 'October', 'November','December'],[1,2,3,4,5,6,7,8,9,10,11,12]).astype(str).astype(int)
enter image description here This is the month in the original dataset and I want it to be represented as a number For example January = 1, February = 2
refer to the python code how to replace month name with number in R.Thanks for your help.
CodePudding user response:
I think you are looking for match
and month.names
:
# setup
dat <- data.frame(month_name = month.name[sample(1:12, size = 12)])
dat
#> month_name
#> 1 June
#> 2 October
#> 3 November
#> 4 May
#> 5 February
#> 6 July
#> 7 April
#> 8 December
#> 9 September
#> 10 January
#> 11 March
#> 12 August
# turn month names into numbers
dat$month_no <- match(dat$month_name, month.name)
dat
#> month_name month_no
#> 1 June 6
#> 2 October 10
#> 3 November 11
#> 4 May 5
#> 5 February 2
#> 6 July 7
#> 7 April 4
#> 8 December 12
#> 9 September 9
#> 10 January 1
#> 11 March 3
#> 12 August 8
Created on 2022-05-25 by the reprex package (v2.0.1)
CodePudding user response:
df[,'new_col'] <- NA
df$new_col[df$old_col == "January"] <- 1
df$new_col[df$old_col == "February"] <- 2
and so on