簡體   English   中英

如何刪除除月的最后日期以外的所有日期的行?

[英]How to delete rows for all dates except the last date of the month?

我正在使用r中的時間序列,其中包含來自北歐證券交易所的每日觀察。 我只想保留每個公司(列)的月份的最后日期。

我的數據框OSE看起來像這樣(但是有幾千行和幾列):

Date           Statoil     DNB
1987-09.16     0,21        1,2
1987-09.17     0,22        1,3
1987-09.18     0,15        1,1
1987-09.21     0,16        1,5
1987-09.22     0,27        1,7
1987-09.23     0,28        1,9
1987-09.24     0,30        1,6
1987-09.25     0,32        1,7
1987-09.28     0,29        1,8
1987-09.29     0,33        2,1
1987-09.30     0,34        1,9
1987-10.01     0,37        1,8
1987-10.02     0,38        2,1
1987-10.05     0,34        2,3
1987-10.06     0,28        2,4
1987-10.07     0,27        2,1
1987-10.08     0,25        2,2
1987-10.09     0,21        2,1
1987-10.12     0,31        1,9
1987-10.13     0,31        2,1
1987-10.14     0,32        2,3
1987-10.15     0,37        2,5
1987-10.16     0,41        2,6
1987-10.19     0,51        2,8
1987-10.20     0,62        3,1
1987-10.21     0,59        3,1
1987-10.22     0,58        3,5
1987-10.23     0,61        3,6
1987-10.26     0,62        3,7
1987-10.27     0,63        3,9
1987-10.28     0,57        4,0
1987-10.29     0,54        4,1
1987-10.30     0,64        4,1
1987-11.02     0,66        4,2
1987-11-03     0,67        3,9

我希望它看起來像這樣:

Date           Statoil     DNB
1987-09.30     0,34        1,9
1987-10.30     0,64        4,1

你們對於刪除多余的行(即不是該月的最后日期的行)有什么建議嗎?

感謝所有的幫助!

我們可以在tidyverse執行相同的策略, tidyverse和年分組:

library(tidyverse)
library(lubridate)

tib$Date <- ymd(tib$Date) # parse .$Date to date class

tib %>% arrange(desc(Date)) %>% # order dates last to first
    group_by(month(Date), year(Date)) %>%
    slice(1)

# A tibble: 3 x 5
# Groups:   month(Date), year(Date) [3]
Date Statoil    DNB `month(Date)` `year(Date)`
<date>  <fctr> <fctr>         <dbl>        <dbl>
1 1987-09-30    0,34    1,9             9         1987
2 1987-10-30    0,64    4,1            10         1987
3 1987-11-03    0,67    3,9            11         1987

在該示例中,沒有“ Company列,因此似乎我們需要按“月”分組並獲取max日期行

library(data.table)
setDT(df1)[, Date := as.IDate(Date, "%Y-%m.%d")]
df1[df1[, .I[which.max(Date)] ,
     .(month = month(Date), year = year(Date))]$V1]
#         Date Statoil DNB
#1: 1987-09-30    0,34 1,9
#2: 1987-10-30    0,64 4,1
#3: 1987-11-03    0,67 3,9

您可能需要考慮將數據集轉換為xts格式,然后使用to.period()命令,該命令可以快速,輕松地工作。 例如,讓我們創建一個假的每日時間序列,然后在每個月末將最后一個值子集化:

library(xts)
set.seed(78)
date.a <-seq(as.Date("2000/10/1"), as.Date("2000/12/31"), "days")
dat <-xts(rnorm(length(date.a)), date.a)
dat.month.end <-to.period(dat, period='months', indexAt='lastof', OHLC=F)

dat.month.end
                  [,1]
2000-10-31  1.00117650
2000-11-30 -1.15090619
2000-12-31  0.04944459

暫無
暫無

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

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