【问题标题】:How to count the month that you don't have any new client [duplicate]如何计算没有新客户的月份[重复]
【发布时间】:2019-09-02 12:02:22
【问题描述】:

我在客户的两个日期(date1、date2)和到达日期之间有一个数据框。

date1<- "2019-07-29"
date2<- "2019-09-08"

clients<-data.frame(id= c(1:10),
                    arrive=c("2019-07-31", "2019-07-29", "2019-08-01",
                             "2019-08-03", "2019-08-05", "2019-08-08", 
                             "2019-08-02", "2019-08-06", "2019-09-29", 
                             "2019-09-02"),
                    hotel= c(rep(900067, 5), rep(9001649,5)))

我想计算日期之间,每家酒店有多少个月没有新客户。

酒店 900067 在接下来的第 9 个月没有新客户。酒店 9001649 在第 7 个月没有新客户。

数据框结果应该是这样的:

Result<- data.frame(hotel= c(900067, 9001649), 
                    days_without_new_clients= c(1, 1))

我试过了:

month_between_dates<-function(date1, date2){
  month1<-month(date1)
  month2<-month(date2)
  if(month1>month2){
    result<-c(month1:12, 1:month2)
  } else {
    result<-c(month1:month2)
  }
  return(result)
}
all_hotel_month <- expand.grid(arrive = month_between_dates(date1, date2), hotel = unique(clients1$hotel))
clients1 %>%
  mutate(arrive = month(as.Date(arrive))) %>%
  group_by(hotel)%>% 
  summarize(month_without_new_clients = sum(is.na(id)))

但我得到这个错误:

 Error in summarize(., month_without_new_clients = sum(is.na(id))) : argument "by" is missing, with no default*

【问题讨论】:

  • 你不是刚刚发布了这个问题here吗?
  • 真正相似的问题,但不完全相同。这次我想知道月份。

标签: r date dataframe


【解决方案1】:

使用dplyr,这是一种方法。我们首先在date1date2 之间创建一个日期序列,并得到unique 的月-年组合。我们从clients 中提取月份和年份,并计算每个hotel 没有新客户时的月份数。

unique_my <- unique(format(seq(as.Date(date1), as.Date(date2), "1 day"), "%m-%Y"))

library(dplyr)
clients %>%
   mutate(arrive = as.Date(arrive), 
          month_year = format(arrive, "%m-%Y")) %>%
   group_by(hotel) %>%
   summarise(months_without_new_client = length(setdiff(unique_my, month_year)))

#    hotel months_without_new_client
#    <dbl>                     <int>
#1  900067                         1
#2 9001649                         1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-13
    • 2015-06-20
    • 2013-05-02
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    相关资源
    最近更新 更多