【问题标题】:Sub-setting by partial date r按部分日期 r 子设置
【发布时间】:2018-01-15 20:57:46
【问题描述】:

我正在尝试找到一种方法将 data.frame 子集化为仅来自单个月但多年的记录(即仅来自 4 月但 1900 年、1901 年、1902 年等年的数据)。我正在使用 as.Date 函数将日期信息放入日期类中。这是一个例子:

require("adehabitatHR")
data(teal)
Tdf <- teal
Tdf$date <- as.Date(Tdf$date, "%Y%m%d")

现在要对其进行子集化,我尝试使用和不使用通配符将日期设置为等于月份值:

TdfFeb <- Tdf[Tdf$date == "*-02-*"]
TdfFeb <- Tdf[Tdf$date == "-02-"]

但是,在这两种情况下,我都会收到以下错误:charToDate(x) 中的错误:字符串不是标准的明确格式;这表明 R 没有将我输入的内容识别为合法的日期格式(我也尝试过使用“/”和“。”而不是“-”;所有结果都相同。

我也尝试过将其设置为模式

TdfFeb <- Tdf[Tdf$date == pattern = "-02-"]

当然这也不起作用,由于模式后出现意外的“=”而导致错误。

我意识到,对于这个特定的数据集,只需做一个日期范围就可以了,因为只有 1901 年 2 月的数据;但是,正如我上面所说,我希望能够以这种方式提取多年的数据。如果有人以前遇到过这种情况或有任何建议,我将不胜感激。

【问题讨论】:

  • 试试lubridate 包,它有一个函数month(),它将从日期对象中以整数形式返回月份。

标签: r date subset


【解决方案1】:

由于您有一个有效的日期,您可以使用format 提取月份。

month <- format(Tdf$date, format = "%m")

Tdf[month == "02", ]

               x        y       date
55851  5.9153319 45.44334 1901-02-01
57834  3.3944621 42.64384 1901-02-01
1917   9.9942731 43.42349 1901-02-01
58703  0.7046530 39.45739 1901-02-01
5673   3.2158674 41.60035 1901-02-01
...

【讨论】:

    【解决方案2】:

    你最好使用format

    format(Tdf$date, '%m') == '02'
    

    您的方法的问题是==Dates 进行了重载,并且在与Tdf$date 进行比较之前,R 在内部尝试将-02- 转换为Date。当然-02- 本身并不对应任何日期。格式方法首先将您的Date 转换为character,然后再进行比较。

    一些包(例如lubridatedata.table)具有辅助函数month,它将返回一个数字(特别是在data.tableinteger的情况下)2,它允许类似但可能更易读的方法:

    data.table::month(Tdf$date) == 2L
    

    【讨论】:

      【解决方案3】:

      最好的方法是结合lubridate::monthdplyr::mutate/dplyr::filter

      library("adehabitatHR")
      data(teal)
      library(dplyr)
      library(lubridate)
      # Change column to date and create month column
      teal <- mutate(teal, 
                     date = ymd_hms(date), 
                     month = month(date))
      
      # Filter for month 
      teal %>% filter(month == 2)
                x        y                date month
      1  5.915332 45.44334 1901-02-01 00:29:11     2
      2  3.394462 42.64384 1901-02-01 05:51:41     2
      3  9.994273 43.42349 1901-02-01 07:06:29     2
      4  0.704653 39.45739 1901-02-01 10:03:25     2
      5  3.215867 41.60035 1901-02-01 12:54:33     2
      6  3.275865 43.58711 1901-02-02 00:07:21     2
      7  4.723084 43.49749 1901-02-02 06:53:26     2
      8  1.760862 41.37676 1901-02-02 07:01:53     2
      9  5.814787 41.64366 1901-02-02 13:59:14     2
      10 2.435756 48.94306 1901-02-02 16:04:14     2
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-17
        • 1970-01-01
        • 2017-03-27
        • 2021-11-10
        相关资源
        最近更新 更多