簡體   English   中英

使用R中的xts獲取每周的第一天和最后一天

[英]get first and last day of each week using xts in R

我在這篇文章中讀到了這個夢幻般的解 我想得到兩個時間序列對象。 一個是每周的第一天,另一個是每周的最后一天。 我的時間序列是不規則的,不包括周末和假期。 周從周一到周日。 這是我的系列的開始:

         Date   Val WeekNum
1  01/02/1990 41.38       1
2  02/02/1990 42.88       1
3  05/02/1990 42.00       2
4  06/02/1990 41.50       2
5  07/02/1990 42.25       2
6  08/02/1990 41.75       2
7  09/02/1990 42.13       2
8  12/02/1990 42.13       3
9  13/02/1990 42.00       3
10 14/02/1990 42.63       3
11 15/02/1990 43.75       3
12 16/02/1990 44.75       3
13 20/02/1990 44.13       4
14 21/02/1990 43.88       4
15 22/02/1990 44.38       4
16 23/02/1990 44.00       4
17 26/02/1990 44.00       5
18 27/02/1990 44.88       5
19 28/02/1990 44.50       5
20 01/03/1990 44.63       5
21 02/03/1990 46.00       5
22 05/03/1990 45.88       6
23 06/03/1990 45.50       6
24 07/03/1990 45.38       6
25 08/03/1990 43.63       6
26 09/03/1990 41.50       6
27 12/03/1990 41.38       7
28 13/03/1990 40.63       7
29 14/03/1990 40.25       7
30 15/03/1990 40.50       7
31 16/03/1990 40.50       7
32 19/03/1990 40.25       8
33 20/03/1990 39.88       8
34 21/03/1990 39.75       8
35 22/03/1990 38.50       8
36 23/03/1990 38.75       8
37 26/03/1990 39.63       9
38 27/03/1990 39.75       9

然后我從參考文章中使用:

library(xts)
do.call(rbind, lapply(split(x, "weeks"), function(x) x[1]))

編輯:它沒有工作,因為我有動物園而不是xts的數據。

您可以簡單地使用第firstlast函數。 你也可以使用headtail

# first/last
do.call(rbind, lapply(split(x, "weeks"), first))
do.call(rbind, lapply(split(x, "weeks"), last))
# head/tail
do.call(rbind, lapply(split(x, "weeks"), head, 1))
do.call(rbind, lapply(split(x, "weeks"), tail, 1))

您可以使用.indexwday獲取日期周數。 然后使用range你得到第一個和最后一個。 因為,並非所有周都從周一開始並且周五結束,所以最好每周采取最小值和最大值。

要獲得每周的第一天和最后一天,您可以執行以下操作:

do.call(rbind, lapply(split(dat.xts, "weeks"), 
                      function(y) y[.indexwday(y) %in% range(.indexwday(y))]))



            Val WeekNum
1990-02-01 41.38       1
1990-02-02 42.88       1
1990-02-05 42.00       2
1990-02-09 42.13       2
1990-02-12 42.13       3
1990-02-16 44.75       3
1990-02-20 44.13       4
1990-02-23 44.00       4
1990-02-26 44.00       5
1990-03-02 46.00       5
1990-03-05 45.88       6
1990-03-09 41.50       6
1990-03-12 41.38       7
1990-03-16 40.50       7
1990-03-19 40.25       8
1990-03-23 38.75       8
1990-03-26 39.63       9
1990-03-27 39.75       9

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM