【问题标题】:Subsetting dates in RR中的子集日期
【发布时间】:2021-04-20 08:54:11
【问题描述】:

我有以下数据

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

第一列包含日期(年、月、日、小时)。第二列是降雨量。

日期不是连续的。一些缺少 Rainfall 的日期已被删除。

我想问一下按照年、日、月或小时对这些数据进行子集化的最佳方法是什么?

例如,我只想获取 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 格式化。

我将不胜感激。

林兹

【问题讨论】:

    标签: r


    【解决方案1】:

    如果您想将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
    )
    

    【讨论】:

      【解决方案2】:

      您可以使用lubridate 包和关联的monthyear 函数。

      library(tidyverse)
      library(lubridate)
      
      df <- 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") %>%
        as_tibble()
      
      df %>% 
        mutate(month = lubridate::month(Datetime),
               year = lubridate::year(Datetime))
      

      输出:

      # A tibble: 5 x 4
        Datetime             Rain month  year
        <dttm>              <dbl> <dbl> <dbl>
      1 2009-12-28 16:00:00     0    12  2009
      2 2009-12-28 16:05:00  -999    12  2009
      3 2009-12-28 16:10:00  -999    12  2009
      4 2009-12-28 16:15:00  -999    12  2009
      5 2009-12-28 16:20:00  -999    12  2009
      

      【讨论】:

        猜你喜欢
        • 2019-07-22
        • 1970-01-01
        • 1970-01-01
        • 2020-02-06
        • 1970-01-01
        • 1970-01-01
        • 2022-10-22
        • 1970-01-01
        • 2022-06-24
        相关资源
        最近更新 更多