繁体   English   中英

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

[英]Filter data to keep only the last day of the month

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

原始数据:

         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

所需的 output:

##         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")

我使用 tesseract R package 对问题中的图像进行了 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 class(在 zoo 包中)。 yearmon object 只有年和月(没有日)所以它自然是 forms 年/月组,我们取最后一个。

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")
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

您没有给我们提供数据样本或代码样本——因此投反对票。

1.确保你的数据是一个data.frame (see?data.frame in R)

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),]

暂无
暂无

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

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