簡體   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