0

I would like to map the first/second characters of the column ï..Order.Date to a new column called Order.Month.

ï..Order.Date is a column in the data frame with string dates in M/D/YY or MM/DD/YY format:

"12/1/17" "9/1/17" "9/19/17" "9/1/17" "9/29/17"

I need to create a new column which uses the substring containing the first 1 or 2 characters, and map it to the month:

months = c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')

Still new to r and not sure the best way to approach this.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Joeyboy
  • 432
  • 4
  • 16

2 Answers2

1

We can convert the column to Date class, get the month extracted, convert to numeric and use as index to get the value that corresponds to from the built-in vector month.name

df1$Order.Month <- month.name[as.integer(format(as.Date(df1[["ï..Order.Date"]], 
        format =  "%m/%d/%y"), "%m"))]

Or use lubridate - convert to Date class with mdy, extract the month, use as index in month.name

library(lubridate)
month.name[month(mdy(df1[["ï..Order.Date"]]))]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Works perfectly +10 for speedy reply. How did you know Order.Date was the first column in my DataFrame? Was it because of the prefix? – Joeyboy Sep 22 '21 at 06:01
  • 1
    @Joeyboy that was just a guess. I updated with the actual column name. it is just that there are some unusual characters in the name, that I was not sure whether it is a typo or not – akrun Sep 22 '21 at 06:03
0

Once you create a date object you can use format(..., '%B') to get the month name.

x <- c("12/1/17", "9/1/17", "9/19/17", "9/1/17", "9/29/17")
format(lubridate::mdy(x), '%B')

#[1] "December"  "September" "September" "September" "September"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213