# How do I sort dates by month in R?

## How do I sort dates by month in R?

Contents

Problem Description:

new R student here. I am trying to sort data by month. Here is a sample of the data I need to use, followed by the code, then my results. Any tips for how to accomplish this?! I’m super stuck…

This is the latest code I have been trying:

`````` library(readr)
weather <- read_csv("R/weather.csv", col_types = cols(High = col_number(),
Low = col_number(), Precip = col_number(),
Snow = col_number(), Snowd = col_integer()))
View(weather)

library(ggplot2)
library(ggridges)
library(dplyr)
library(lubridate)

class(weather)  #what class is dataset = dataframe

weather.month <- weather %>%   # Group data by month
mutate(weather, 'month') %>%
group_by(month = lubridate::floor_date(weather\$Day, 'month')) %>%
summarise(weather.month\$High)
``````

Then this is the errors I get:

Any help getting through this would be greatly appreciated!!!

## Solution – 1

The code can be modified by converting the `Day` to `Date` class (with `mdy` or `dmy` – as it is not clear whether it is month-day-year or day-month-year format), then apply the `floor_date` by ‘month’ and apply the function on High column

``````library(dplyr)
library(lubridate)
weather %>%   #
group_by(month = lubridate::floor_date(mdy(Day), 'month')) %>%
summarise(High = sum(High, na.rm = TRUE))
``````
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.