确定日期范围内的唯一年份

问题描述 投票:1回答:2

我正在尝试确定客户在几年内使用医疗保健。数据:

Clientnumber   Date start  Date end
1              01-03-2017  31-10-2017
1              01-02-2018  07-08-2018
1              01-11-2018  01-03-2019
1              25-03-2019  01-07-2020

For this one client I want to know in what unique years he/she is registered. Thus, the result should be:
2017, 2018, 2019, 2020 and additonally a count of unique years: 4.

是否可以在Excel或R中做到这一点?

谢谢。

r excel excel-formula rstudio
2个回答
0
投票

在R中,我们可以获取长格式的数据,将其转换为Date并提取Year。对于每个客户,我们可以创建一个逗号分隔的unique Year值和不同的Year计数。

library(dplyr)

df %>%
  tidyr::pivot_longer(cols = -Clientnumber) %>%
  mutate(value = as.Date(value, "%d-%m-%Y"), 
         Year = format(value, "%Y")) %>%
  group_by(Clientnumber) %>%
  summarise(Un_year = toString(unique(Year)), 
            count = n_distinct(Year)) 

# Clientnumber  Un_year                count
#         <int> <chr>                  <int>
#1            1 2017, 2018, 2019, 2020     4

0
投票

dplyrpurrr一个选项可以是:

df %>%
 group_by(Clientnumber) %>%
 summarise(Years = map_chr(list(c(Date_start, Date_end)), 
                           ~ toString(unique(substr(., 7, 10)))))

  Clientnumber Years                 
         <int> <chr>                 
1            1 2017, 2018, 2019, 2020

[如果还要计数,请加上stringr

df %>%
 group_by(Clientnumber) %>%
 summarise(Years = map_chr(list(c(Date_start, Date_end)), 
                           ~ toString(unique(substr(., 7, 10)))),
           n = str_count(Years, ",")+1)

  Clientnumber Years                      n
         <int> <chr>                  <dbl>
1            1 2017, 2018, 2019, 2020     4

如果情况稍微复杂一些,则意味着您希望从第一年到最后一年之间的所有年份,即使它们不在数据中:

df %>%
 group_by(Clientnumber) %>%
 summarise(Years = map_chr(list(c(Date_start, Date_end)), 
                           ~ toString(reduce(range(as.numeric(substr(., 7, 10))), `:`))),
           n = str_count(Years, ",")+1)
© www.soinside.com 2019 - 2024. All rights reserved.