我有以下数据
dat <- structure(list(Datetime = structure(c(1261987200, 1261987500,
1261987800, 1261988100, 1261988400), class = c("POSIXct", "POSIXt"
), tzone = ""), Rain = c(0, -999, -999, -999, -999)), row.names = c(NA,
5L), class = "data.frame")
第一列包含日期(年、月、日、小时)。第二列是降雨量。
日期不连续。一些缺少降雨的日期已经被删除。
我想问一下,根据年、日、月或小时对这些数据进行子集化的最佳方法是什么?
例如,我只想获取 7 月(月 = 7)的所有数据。我所做的是这样的:
dat$month<-substr(dat$Datetime,6,7)
july<-dat[which(dat$month == 7),]
或者如果是一年,比如说 2010 年:
dat$year<-substr(dat$Datetime,1,4)
dat<-which(dat$year == 2010),]
然后将它们转换为数字类型。
在 R 中有没有更简单的方法来做到这一点?日期已经使用 POSIXlt 格式化。
我将不胜感激。
林兹
如果你想转换Datetime
为年或月(数字),你可以尝试format
如下
df1 <- transform(
df,
year = as.numeric(format(Datetime,"%Y")),
month = as.numeric(format(Datetime,"%m"))
)
这给
Datetime Rain year month
1 2009-12-28 09:00:00 0 2009 12
2 2009-12-28 09:05:00 -999 2009 12
3 2009-12-28 09:10:00 -999 2009 12
4 2009-12-28 09:15:00 -999 2009 12
5 2009-12-28 09:20:00 -999 2009 12
如果您想df1
按年份进一步细分(例如,year == 2010
),则
subset(
df1,
year == 2010
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句