如何在每个月的最后一天对数据框进行子集化

问题描述 投票:3回答:3

我有一个df:

     dates  V1  V2  V3  V4  V5  V6  V7  V8  V9  V10
1999-05-31  66  65  64  63  62  61  60  59  58  57
1999-06-01  67  66  65  64  63  62  61  60  59  58
1999-06-02  68  67  66  65  64  63  62  61  60  59
1999-06-03  69  68  67  66  65  64  63  62  61  60
1999-06-04  70  69  68  67  66  65  64  63  62  61
1999-06-17  79  78  77  76  75  74  73  72  71  70
1999-06-18  80  79  78  77  76  75  74  73  72  71
1999-06-21  81  80  79  78  77  76  75  74  73  72
1999-06-22  82  81  80  79  78  77  76  75  74  73
1999-06-23  83  82  81  80  79  78  77  76  75  74
1999-06-24  84  83  82  81  80  79  78  77  76  75
1999-06-25  85  84  83  82  81  80  79  78  77  76
1999-06-28  86  85  84  83  82  81  80  79  78  77
1999-06-29  87  86  85  84  83  82  81  80  79  78
1999-06-30  88  87  86  85  84  83  82  81  80  79

我想在每个月的最后一天将上述df分配。也就是说,只有1999-05-31和1999-06-30的日期才会出现。实际的数据框架要大得多,最后的日期可能是每个月的第28个,第29个等等。所以我希望输出类似于:

dates   V1  V2  V3  V4  V5  V6  V7  V8  V9  V10
1999-05-31  66  65  64  63  62  61  60  59  58  57 
1999-06-30  88  87  86  85  84  83  82  81  80  79
1999-10-29  175 174 173 172 171 170 169 168 167 166

我试图在动物园或其他包装中找到一些功能,但找不到一个......对所有建议都很满意!

r xts zoo
3个回答
2
投票

这将选择该月的最后几天:

df[as.numeric(substr(as.Date(df$dates) + 1, 9, 10))
   < as.numeric(substr(df$dates, 9, 10)), ]

#        dates V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#1  1999-05-31 66 65 64 63 62 61 60 59 58  57
#15 1999-06-30 88 87 86 85 84 83 82 81 80  79

请注意,此解决方案取决于每天的绝对月数(无论您的数据如何)。

如果要在实际数据中选择每月的最后一天,请使用以下命令:

df[c(diff(as.numeric(substr(df$dates, 9, 10))) < 0, TRUE), ]

3
投票

假设日期格式正确为日期,源数据框为x

> library(xts)
> x[endpoints(x$dates, on = "months"), ]
        dates V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  1999-05-31 66 65 64 63 62 61 60 59 58  57
15 1999-06-30 88 87 86 85 84 83 82 81 80  79

0
投票

这是一个使用dplyr的选项:

library(dplyr)

df %>% 
  mutate(dates = as.Date(dates)) %>% 
  mutate(yr_mnth = format(dates, '%Y-%m')) %>% 
  group_by(yr_mnth) %>% 
  filter(dates == max(dates))

# or if you wanted the first observation of each month:
df %>% 
  mutate(dates = as.Date(dates)) %>% 
  mutate(yr_mnth = format(dates, '%Y-%m')) %>% 
  group_by(yr_mnth) %>% 
  filter(dates == min(dates))
© www.soinside.com 2019 - 2024. All rights reserved.