Home > Net >  How do i get the number of each month?
How do i get the number of each month?

Time:04-28

I have a data frame with a column of date objects. How can i get a new column with the number of a month? example: January -> 1, february -> 2 ...

I need a new column with the numbers of each day of the month, too. example: 2022-01-01 -> 1 , 2022-01-02 - 2

CodePudding user response:

I'm sure there are date object-specific solutions in R, but I've never used them. A base R solution:

splitDates <- function( date ) {
  
  day <- gsub('^0 ','',strsplit(date,'-')[2])
  month <- gsub('^0 ','',strsplit(date,'-')[3])
  
  return(list(day,
              month))
  
}

CodePudding user response:

You can use the following code:

df = data.frame(date = as.Date(c("2022-01-01", "2022-01-02")))
df[, "month"] <- format(df[,"date"], "%m")
df

Output:

        date month
1 2022-01-01    01
2 2022-01-02    01
  • Related