So i have a dataframe in R:
Date
2002-01-24
2003-02-25
2004-03-26
and when i check the data type of the Date column,
str(df$Date)
it is of "Date" type.
Now, i want to create a new column named "Month", which i would take the portion of year and month in the Date column, without the day.
Date Month
2002-01-24 2002-01
2003-02-25 2003-02
2004-03-26 2004-03
The way i did it is below:
df$Month <- format(as.Date(df$Date), "%Y-%m"))
but when i run
str(df$Month)
it says it is of "chr" type instead of "Date" . Is there any ways to keep it in the "Date" data type instead of being converted to chr?
The Date
class describes a particular day. (BTW, the internal representation is the number of days since 1970-01-01.) So, you can't have a Date
without specifying a day.
If you want to keep the Date
class when denoting a particular month you can round down to the first day of the month :
lubridate::floor_date(as.Date("2019-04-19"), "month")
which will return 2019-04-01
.
With OP's data:
df <- data.frame(Date = as.Date(c("2002-01-24", "2003-02-25", "2004-03-26")))
df$Month <- lubridate::floor_date((df$Date), "month")
df
Date Month 1 2002-01-24 2002-01-01 2 2003-02-25 2003-02-01 3 2004-03-26 2004-03-01
str(df)
'data.frame': 3 obs. of 2 variables: $ Date : Date, format: "2002-01-24" "2003-02-25" "2004-03-26" $ Month: Date, format: "2002-01-01" "2003-02-01" "2004-03-01"
This is very handy for plotting monthly aggregates.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.