Home > OS >  Set 2 digits in Month
Set 2 digits in Month

Time:03-10

I have a DF and I would like to create a column with YEAR and MONTH, but setting 2 digits for the month. See my code:

ID <- c(111,222,333,444,555)
DATE <- c(as.Date(c('10/10/2021','12/11/2021','30/12/2021','20/01/2022','25/02/2022') ,"%d/%m/%Y"))
DF_1 <- data.frame(ID, DATE)

Adding the YEAR and MONTH column:

DF_2 <- DF_1 %>%
mutate(YEAR_MONTH = paste(lubridate::year(DATA),
lubridate::month(DATE),
sep = ""))

As you can see, in IDs 444 and 555 the month only presented one digit. I would like it to look like this:

ID <- c(111,222,333,444,555)
DATE <- c(as.Date(c('10/10/2021','12/11/2021','30/12/2021','20/01/2022','25/02/2022') ,"%d/%m/%Y"))
YEAR_MONTH <- c('202110','202111','202112','202201','202202')
DF_3 <- data.frame(ID, DATE, YEAR_MONTH)

How would I go about treating these months that are showing up with just one digit?

Grateful.

CodePudding user response:

Instead of using lubridate year/month, we can directly modify with format which returns the 4 digit year and 2 digit month. lubridate returns a numeric/integer value which cannot have 0 as padding on the left

library(dplyr)
DF_1 <- DF_1 %>%
    mutate(YEAR_MONTH = format(DATE, "%Y%m"))

Or using base R

DF_1$YEAR_MONTH <- with(DF_1, format(DATE, "%Y%m"))
  •  Tags:  
  • r
  • Related