过滤数据以仅保留该月的最后一天

时间:2017-12-21 14:29:14

标签: r date

我有每日数据,我想从中提取每个月的最后一天

原始数据:

         Date    Value
20 2008-01-28 82.55261
21 2008-01-29 83.43333
22 2008-01-30 83.07948
23 2008-01-31 84.22759
24 2008-02-01 85.77670
25 2008-02-04 84.87240
26 2008-02-05 82.58407
27 2008-02-06 81.77103
28 2008-02-07 80.78428
29 2008-02-08 81.51842
30 2008-02-11 82.39453
31 2008-02-12 84.09175
32 2008-02-13 85.58366
33 2008-02-14 83.77604

期望的输出:

##         Date    Value
## 1 2008-01-31 84.22759
## 2 2008-02-14 83.77604

G. Grothendieck从这个问题的最早版本中发布的屏幕截图中精心整理了数据:

structure(list(Date = structure(c(13906, 13907, 13908, 13909, 
13910, 13913, 13914, 13915, 13916, 13917, 13920, 13921, 13922, 
13923), class = "Date"), Value = c(82.552612, 83.433327, 83.079483, 
84.227585, 85.776695, 84.872398, 82.584068, 81.771027, 80.784279, 
81.518417, 82.39453, 84.091751, 85.583664, 83.776039)), row.names = c("20", 
"21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", 
"32", "33"), class = "data.frame")

3 个答案:

答案 0 :(得分:3)

我使用tesseract R软件包对问题中的图像进行了OCR并手动修复了它产生的错误,但是将来请提供一个可以直接复制并粘贴到R中的表单的输入。 DF是减少到适当大小的输入,然后可以使用dput(DF)的输出。请参阅本答案末尾的注释。

以下是两种方法:

1)substr 这个单行使用日期的前6个字符(即年和月),并使用它来查找如此形成的每个组中的最后一行。没有包使用。

subset(DF, !duplicated(substr(V1, 1, 6), fromLast = TRUE))
##          V1       V2
## 23 20080131 84.22759
## 33 20080214 83.77604

2)yearmon 另一种可能性是使用yearmon类(在动物园包中)。一个yearmon对象只有年和月(没有一天)所以它自然形成年/月组,我们采取最后一个。

library(zoo)

subset(DF, !duplicated(as.yearmon(as.character(V1), "%Y%m"), fromLast = TRUE))
##          V1       V2
## 23 20080131 84.22759
## 33 20080214 83.77604

注意

DF <- structure(list(V1 = c(20080128L, 20080129L, 20080130L, 20080131L, 
20080201L, 20080204L, 20080205L, 20080206L, 20080207L, 20080208L, 
20080211L, 20080212L, 20080213L, 20080214L), V2 = c(82.552612, 
83.433327, 83.079483, 84.227585, 85.776695, 84.872398, 82.584068, 
81.771027, 80.784279, 81.518417, 82.39453, 84.091751, 85.583664, 
83.776039)), .Names = c("V1", "V2"), row.names = c("20", "21", 
"22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", 
"33"), class = "data.frame")

答案 1 :(得分:1)

library(dplyr)

df$mon_yr = format(df$date, "%Y-%m") 
# creates an identifier with which to group

df %>% group_by(mon_yr) %>% filter(date == max(date))
#groups by created month identifier and then keeps only those rows with last(max) date

答案 2 :(得分:-4)

您没有向我们提供数据样本或代码示例 - 因此是downvotes。

1。确保您的数据为data.frame(请参阅R中的?data.frame)

df <- myexcelfile # Pseudocode - will not run!

2. 确保V1是日期列。确保将其编码为日期(请参阅R中的?as.Date)。

df$Date <- as.Date(df$Date, format = "%d%m%Y")

3. 过滤最早日期的数据框架:

df[which.max(df$Date),]