返回日期范围(按组) [英] Return date range by group

查看:103
本文介绍了返回日期范围(按组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按颜色分组并计算该颜色的日期范围。我试过 group_by() summarize() aggregate()

I want to group by color and calculate the date range for that color. I have tried group_by(), summarize() and aggregate().

#Data:
df1 <- as.Date(c('Jul 1', 'Jun 26', 'July 5', 'July 15'), format = '%B %d')
df2 <- c("red", "blue", "red", "blue")

df1 <- data.frame(df1,df2)

我是什么尝试获取:

#  Group.1   x
[1]   4     red
[2]   19    blue 

我一直在尝试:

df <- aggregate(df1[,1], list(df1[,2]), as.numeric(max(df1[,1]) - min(df1[,1]), units="days"))

我已经测试了 as。 numeric(max(df1 [,1])-min(df1 [,1]),units = days),它返回我要查找的值,但我无法弄清楚如何为每种颜色返回该值。

I have tested as.numeric(max(df1[,1]) - min(df1[,1]), units="days") and it returns the value that I'm looking for, I just can't figure out how to return that value for each color.

下面是我的错误消息,但实际上,我只是以错误的方式进行操作。

My Error Message is below, but I think realistically, I'm just going about this the wrong way.

 Error in match.fun(FUN) : 
      'as.numeric(max(df1$date) - min(df1$date), units = "days")' is not a function, character or symbol

阅读 aggregate()文档后,我尝试对最后一个参数使用 formula = 并返回此错误:

after reading through aggregate() document I tried to use the formula = for the last argument and returned this error:

match.fun(FUN)中的错误:缺少参数 FUN,没有默认值

推荐答案

使用 dplyr

 df1 %>% 
   group_by(df2) %>% 
   summarise(Range=max(df1) - min(df1))
# A tibble: 2 x 2
  df2   Range  
  <fct> <drtn> 
1 blue  19 days
2 red    4 days

这篇关于返回日期范围(按组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆