代码之家  ›  专栏  ›  技术社区  ›  Brent

部分日期r的子设置

  •  1
  • Brent  · 技术社区  · 8 年前

    我试图找到一种方法来对数据进行子集。仅帧到单个月但跨多个年份的记录(即仅从1900年、1901年、1902年等4月份开始的数据)。我正在使用as将日期信息放入日期类中。日期函数。以下是一个示例:

    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月的数据;然而,正如我上面所说,我希望能够以这种方式提取多年的数据。如果有人以前遇到过这种情况或有什么建议,我将不胜感激。

    3 回复  |  直到 8 年前
        1
  •  0
  •   Roman LuÅ¡trik    8 年前

    由于您有一个有效日期,因此可以使用 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
  •  0
  •   MichaelChirico    8 年前

    你最好用这样的东西 format :

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

    你的方法的问题是 == 已重载 Date s、 而内部R正试图转换 -02- 到a 日期 比较之前 Tdf$date . 当然 -02- 它本身与任何日期都不对应。格式方法转换 日期 character 比较前先进行。

    几个包(例如。 lubridate , data.table )具有助手功能 month 它将返回一个数字(特别是在 数据桌子 , integer ) 2 这允许采用类似但可能更具可读性的方法:

    data.table::month(Tdf$date) == 2L
    
        3
  •  0
  •   Colin FAY    8 年前

    最好的方法是组合 lubridate::month dplyr::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
    ...
    
    推荐文章