【问题标题】:Extract datetime value where time is minimal R提取时间最小的日期时间值 R
【发布时间】:2020-07-15 17:38:18
【问题描述】:

我正在使用 suncalc 包为一组具有纬度/经度坐标的日期生成阳光时间。下面是一些示例代码:

library(tidyverse)
library(hms)
library(lubridate)
library(suncalc)

data <- structure(list(date = structure(c(17975, 18044, 18231, 18172, 
18169), class = "Date"), lat = c(40.7128, 41.8781, 34.0522, 25.7617, 
39.9526), lon = c(-74.006, -87.6298, -118.2437, -80.1918, -75.1652
)), class = "data.frame", row.names = c(NA, -5L))

data
        date     lat       lon
1 2019-03-20 40.7128  -74.0060
2 2019-05-28 41.8781  -87.6298
3 2019-12-01 34.0522 -118.2437
4 2019-10-03 25.7617  -80.1918
5 2019-09-30 39.9526  -75.1652

从那里,生成每天和给定时区的日出和日落时间是相当简单的:

data %>% 
  getSunlightTimes(data = ., keep = c("sunrise", "sunset"), tz = "America/Los_Angeles")

        date     lat       lon             sunrise              sunset
1 2019-03-20 40.7128  -74.0060 2019-03-20 04:01:11 2019-03-20 16:08:32
2 2019-05-28 41.8781  -87.6298 2019-05-28 03:21:36 2019-05-28 18:16:52
3 2019-12-01 34.0522 -118.2437 2019-12-01 06:41:42 2019-12-01 16:45:14
4 2019-10-03 25.7617  -80.1918 2019-10-03 04:14:55 2019-10-03 16:07:12
5 2019-09-30 39.9526  -75.1652 2019-09-30 03:56:49 2019-09-30 15:47:06

生成的日出和日落值属于 POSIXct 类,同时表示日期和时间信息。从这里,我想做的是提取时间最短的日出值,无论日期如何。因此,在这种情况下,我要提取的值是日出列第 2 行中的数据。结果应具有完整的日期和时间信息,但该值是根据时间标准而不是日期选择的。

任何帮助将不胜感激!

【问题讨论】:

    标签: r tidyverse lubridate posixct


    【解决方案1】:

    转换成ITime后可以使用slice

    library(data.table)
    library(dplyr)
    data %>% 
       getSunlightTimes(data = ., keep = c("sunrise", "sunset"),
            tz = "America/Los_Angeles") %>% 
       slice(which.min(as.ITime(sunrise)))
    # date     lat      lon             sunrise              sunset
    #1 2019-05-28 41.8781 -87.6298 2019-05-28 03:21:36 2019-05-28 18:16:52
    

    或者使用base R,如果我们format,我们可以更轻松地做到这一点,将“日期”部分更改为通用日期并使用which.min

    data[with(data, which.min(as.POSIXct(format(sunrise, "2020-01-01 %H:%M:%S")))),]
    #        date     lat      lon             sunrise              sunset
    #2 2019-05-28 41.8781 -87.6298 2019-05-28 03:21:36 2019-05-28 18:16:52
    

    【讨论】:

      【解决方案2】:

      在基础 R 中:

      data$time_only <- strftime(df$sunrise, format="%H:%M:%S", tz = "America/Los_Angeles")
      data[as.character(data$time_only) == min(data$time_only), -ncol(data)]
      

      输出

      # date     lat      lon             sunrise              sunset
      # 2019-05-28 41.8781 -87.6298 2019-05-28 03:21:36 2019-05-28 18:16:52
      

      【讨论】:

        猜你喜欢
        • 2021-12-23
        • 2014-11-20
        • 2020-12-19
        • 2017-02-13
        • 2015-11-04
        • 1970-01-01
        • 2019-05-31
        • 2015-10-17
        • 1970-01-01
        相关资源
        最近更新 更多