计算在一个范围内出现设定次数的唯一值的数目

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

我在Excel中有一个如下所示的数据集:

A    B            C
ID   Start_date   End_date
1    01/01/2000   05/01/2000
1    06/01/2000   15/05/2000
1    16/05/2000   07/04/2018
2    06/07/2016   09/10/2019
2    10/10/2019   14/12/2019
3    02/08/2000   06/08/2006
3    07/08/2006   15/02/2020
4    05/09/2012   09/11/2017

我想在上述数据集中创建一个唯一值数量的时间序列,该值在该数据集所覆盖的日期范围内的任何月份之前的12个月中出现了3次以上(在本例中为01/01 / 2000-15/02/2020)。因此,例如,在2001年1月之前的12个月中出现的唯一值超过3次的数量为1(ID = 1)。

我已经使用以下公式在Excel中进行了尝试:

{=SUM(--(FREQUENCY(IF(($B$2:$B$8<=EOMONTH('Time Series'!A2,0))*($C$2:$C$8>=EOMONTH('Time Series'!A2,-12),$A$2:$A$8),$A$2:$A$8)>0))}

[C0中的值为2001年1月。

但是,它只返回2001年1月之前的12个月中出现的唯一值的数量,而不是此期间出现超过3次的唯一值的数量。

对此的任何帮助将不胜感激-到目前为止,我一直在Excel中进行此操作,如果这样会更简单,我将愿意在R中执行计算。

r excel countif
1个回答
1
投票

不确定我是否正确理解了您的问题:

1。创建最小可重复的示例:

'Time Series'!A2

返回:

df <-structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 4L),
               Start_date = c("01/01/2000", "06/01/2000", "16/05/2000", "06/07/2016", "10/10/2019", "02/08/2000", "07/08/2006", "05/09/2012"),
               End_date = c("05/01/2000", "15/05/2000","07/04/2018", "09/10/2019", "14/12/2019", "06/08/2006", "15/02/2020", "09/11/2017")),
          class = "data.frame", row.names = c(NA, -8L))

head(df)
  1. 使用dplyr的建议解决方案

格式化日期列 ID Start_date End_date 1 1 01/01/2000 05/01/2000 2 1 06/01/2000 15/05/2000 3 1 16/05/2000 07/04/2018 4 2 06/07/2016 09/10/2019 5 2 10/10/2019 14/12/2019 6 3 02/08/2000 06/08/2006

as.Date

返回:

library(dplyr)
df_formated <- df %>% 
  mutate(Start_date = as.Date(Start_date, "%d/%m/%Y"),
         End_date = as.Date(End_date, "%d/%m/%Y"))

str(df)

'data.frame': 8 obs. of 3 variables: $ ID : int 1 1 1 2 2 3 3 4 $ Start_date: chr "01/01/2000" "06/01/2000" "16/05/2000" "06/07/2016" ... $ End_date : chr "05/01/2000" "15/05/2000" "07/04/2018" "09/10/2019" ... 过滤并计数出现次数,并按cutoff_date过滤:

min_number_of_occurences

返回:

cutoff_date <- as.Date("01/01/2001", "%d/%m/%Y")
min_number_of_occurences <- 3

df_formated %>% 
  filter(Start_date < cutoff_date) %>% 
  group_by(ID) %>% 
  summarise(N = n()) %>% 
  filter(N >= min_number_of_occurences)
© www.soinside.com 2019 - 2024. All rights reserved.