按R中的日期对数据帧进行分组

时间:2017-06-20 18:23:45

标签: r date group-by

我将数据读入R中的数据框。我希望能够将所有与月份对应的日期的数据分组到一个名为" 1月和#34;的新类别,或者无论它是什么月份。例如,如果我有一行看起来像这样

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

我希望它看起来像这样:

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

我尝试过的事情:

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))

我想实施一种类似的方法,除了不是将日期设置为不是&#34; NA&#34;我希望他们在任何月份进行评估,因此我不必创建12个数据帧并删除每个数据帧。我想我可以通过在group_by(ifelse)()中实施多个条件来实现,但我不确定如何。

以下是样本数据的输入:

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"))

1 个答案:

答案 0 :(得分:1)

使用lubridatedplyr

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

将输出整数月份。带有列表的另一个变异应该可以让你一路走来。