繁体   English   中英

如何从 R 中的日期系列开始 select 一个月中的最早日期?

[英]How to select the earliest date in a month from a Date series in R?

我有一个数据库,其中包含具有不同频率(每周、每月、每天)数据的不同指数的值。 我希望通过从时间序列中提取月初值来计算月收益。

我尝试使用循环逐月对时间序列进行分区,然后使用 min() 来获取该月的最早日期。 但是,我想知道是否有更有效的方法来加快计算速度。

library(data.table)
df<-fread("statistic_date index_value funds_number
           2013-1-1    1000.000            0
           2013-1-4     996.096           21
           2013-1-11    1011.141           21
           2013-1-18    1057.344           21
           2013-1-25    1073.376           21
           2013-2-1    1150.479           22
           2013-2-8    1150.288           19
           2013-2-22    1112.993           18
           2013-3-1    1148.826           20
           2013-3-8    1093.515           18
           2013-3-15    1092.352           17
           2013-3-22    1138.346           18
           2013-3-29    1107.440           17
           2013-4-3    1101.897           17
           2013-4-12    1093.344           17")

我希望过滤以获取每个月最早日期的行,例如:

2013-1-1    1000.000            0
2013-2-1    1150.479           22
2013-3-1    1148.826           20
2013-4-3    1101.897           17

您的帮助将不胜感激!

使用 tidyverse 和 lubridate 包,

library(lubridate)
library(tidyverse)
df %>% mutate(statistic_date = ymd(statistic_date), # convert statistic_date to date format
              month = month(statistic_date),  #create month and year columns
              year= year(statistic_date)) %>%
       group_by(month,year) %>% # group by month and year
       arrange(statistic_date) %>% # make sure the df is sorted by date
       filter(row_number()==1) # select first row within each group



# A tibble: 4 x 5
# Groups:   month, year [4]
#  statistic_date index_value funds_number month  year
#  <date>               <dbl>        <int> <dbl> <dbl>
#1 2013-01-01           1000             0     1  2013
#2 2013-02-01           1150.           22     2  2013
#3 2013-03-01           1149.           20     3  2013
#4 2013-04-03           1102.           17     4  2013

首先将statistic_date设为日期:

df$statistic_date <- as.Date(df$statistic_date)

您可以使用nth_daystatistic_date中查找每个月的第一天。

library("datetimeutils")
dates <- nth_day(df$statistic_date, period = "month", n = "first")
## [1] "2013-01-01" "2013-02-01" "2013-03-01" "2013-04-03"

df[statistic_date %in% dates]
##    statistic_date index_value funds_number
## 1:     2013-01-01    1000.000            0
## 2:     2013-02-01    1150.479           22
## 3:     2013-03-01    1148.826           20
## 4:     2013-04-03    1101.897           17

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM