首页 > 解决方案 > 我可以使用 suncalc 创建一个数据表,其中包含每个日期的日出和日落时间以及各个地理位置吗?

问题描述

我正在尝试为function一个州的各个县写一个输出一年中每一天的日出和日落时间。目前,我有一个table用于县及其latitudes和的列longitudes,例如:

纬度 经度
大章克申 65 -80
拉里默 62 -75

我还为我感兴趣的那一年生成table了一个:dates

start.date = "20200101"; end.date = "20201231"
Dates <- seq(ymd(start.date), ymd(end.date), by = "days")

我有suncalc-package 可用于计算各个日期的日出和日落时间,例如:

library(suncalc)

getSunlightTimes(date = 20200101, lat = 65, lon = -80, tz = "MST")

data.frame知道了这一点,在一年中的每一天为每个县生成日出和日落时间的最佳方法是什么?

部分原因是我对如何table正确提取代码以避免输入数百次代码感到困惑,另一部分是担心让它看起来干净且易于导航(但我知道有这么多值这可能是不可避免的)。

标签: rdataframedate

解决方案


这是一种方法:

my_df <- data.frame(
  County = c("Grand Junction", "Larimer"),
  Latitude = c(65,62),
  Longitude = c(-80,-75)
)

# install.packages("suncalc")
library(suncalc)
# install.packages("lubridate")
library(lubridate)
start.date = "20200101"; end.date = "20201231"
Dates <- seq(ymd(start.date),ymd(end.date), by = "days")
# install.packages("tidyverse")
library(tidyverse)
sun_df <- expand.grid(Dates = Dates,County = my_df$County) %>% 
  left_join(my_df) %>%
  group_by(Dates, County, Latitude, Longitude) %>% 
  mutate(sunrise = getSunlightTimes(Dates,Latitude,Longitude,tz = "MST")$sunrise,
         sunset = getSunlightTimes(Dates,Latitude,Longitude,tz = "MST")$sunset)  

这将在一个表中提供您想要的信息,而无需专门为每个县编码:

> head(sun_df)
# A tibble: 6 × 6
# Groups:   Dates, County, Latitude, Longitude [6]
  Dates      County         Latitude Longitude sunrise            
  <date>     <chr>             <dbl>     <dbl> <dttm>             
1 2020-01-01 Grand Junction       65       -80 2020-01-01 08:28:20
2 2020-01-02 Grand Junction       65       -80 2020-01-02 08:27:05
3 2020-01-03 Grand Junction       65       -80 2020-01-03 08:25:41
4 2020-01-04 Grand Junction       65       -80 2020-01-04 08:24:10
5 2020-01-05 Grand Junction       65       -80 2020-01-05 08:22:32
6 2020-01-06 Grand Junction       65       -80 2020-01-06 08:20:46
# … with 1 more variable: sunset <dttm>

推荐阅读