r - 我可以使用 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
正确提取代码以避免输入数百次代码感到困惑,另一部分是担心让它看起来干净且易于导航(但我知道有这么多值这可能是不可避免的)。
解决方案
这是一种方法:
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>
推荐阅读
- python - pyspark数据框父子层次结构问题
- php - 致命错误:未捕获的错误:在 Y 上调用成员函数 X
- 3d - Maxscript netrender 文件名 - 尝试在不附加帧号的情况下保存
- java - 为网格图像提供共享选项
- python - 使用 Asyncio 在 Djano 视图中异步运行 10 个函数
- android - 错误“打开失败:ENOENT(没有这样的文件或目录)”
- openssl - 在 OMNeT++ 的 INET 框架中包含 openssl 库
- python-3.x - 噪声数据的等高线图 - 网格化和平均化
- javascript - React-three-fiber 'useRender' 不是从'react-three-fiber' 导出的
- git - 如何确保 git 超级项目引用的所有子模块提交都有效(并保持有效)?