Caitlynn Birch
Caitlynn Birch

Reputation: 1

Adding a new column with month extracted from a separate already existing "date" (mdy) column

a partial clip of the data set

Trying to add a new column in my data table denoting the month (either as a numeric value or character) using an already available column of "SetDate", which is in the format mdy.

I'm new to R and having trouble. Thank you

Upvotes: 0

Views: 1406

Answers (2)

EStark
EStark

Reputation: 193

Try this (created a small example):

library(lubridate)

date_example <- "1/1/92"
lubridate::mdy(date_example)
[1] "1992-01-01"
lubridate::mdy(date_example) %>% lubridate::month()
[1] 1

If you want full month as character string, use:

lubridate::mdy(date_example) %>% lubridate::month(label = TRUE, abbr = FALSE)

Upvotes: 0

12b345b6b78
12b345b6b78

Reputation: 1015

base solution:

f = "%m/%d/%y" # note the lowercase y; it's because the year is 92, not 1992
dataset$SetDateMonth <- format(as.POSIXct(dataset$SetDate, format = f), "%m")

Basically, what it does is it converts the column from character (presumed class) to POSIXct, which allows for an easy extraction of month information.

Quick test:

format(as.POSIXct('1/1/92', format = "%m/%d/%y"), "%m")
[1] "01"

Upvotes: 1

Related Questions