jawz_34
jawz_34

Reputation: 31

Group dataframe by dates in R

I have data read into dataframes in R. I want to be able to group all the data with dates corresponding to month into a new category called "January", or whatever month it is. For instance if I have a row that looks like this

        area  file   `#`     date      time    tmp    lt
         1     c    11     1 17-06-09  1400 35.542    41

I want it to look like this:

            area  file   `#`     date      time    tmp    lt  month
             1     c    11     1 17-06-09  1400 35.542    41  January

What I've tried:

my_df <-my_df %>% group_by(area, month = ifelse(lubridate::month(date) == 1, 'January','na'), hour = cut(time, seq(0, 2400, 100), include.lowest = TRUE)) %>% summarise(temp_mean = mean(temp), temp_sd = sd(temp), lt_mean =mean(intensity), lt_sd = sd(intensity))

I want to implement a similar approach, except instead of making dates that aren't 1 to "NA" I want them to evaluate to whatever month they are, so I don't have to create 12 dataframes and trim out the NAs for each. I think I can do it by implementing multiple conditions in my group_by(ifelse)(), but I'm not sure how.

Here is a dput of sample data:

structure(list(area = c("c", "c", "c", "c", "c", "c"), no = c(11L, 
11L, 11L, 11L, 11L, 11L), date = structure(c(-61661578022, -61661578022, 
-61661578022, -61661578022, -61661578022, -61661578022), class = c("POSIXct", 
"POSIXt"), tzone = ""), time = c(1400, 1500, 1600, 1700, 1800, 
1900), tmp = c(35.542, 28.953, 27.468, 26.977, 25.708, 24.931
), lt = c(41, 4, 1, 1, 0, 0)), .Names = c("area", "no", "date", 
"time", "tmp", "lt"), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

Upvotes: 1

Views: 503

Answers (1)

rsmith54
rsmith54

Reputation: 805

Using lubridate and dplyr:

df %>% mutate(date = lubridate::ydm_hms(date), month = month(date) )

will output with an integer for the months. Another mutate with a list should get you all the way there.

Upvotes: 1

Related Questions