首页 > 解决方案 > 从 NC 文件中提取月度和年度温度数据

问题描述

我已经下载了一个带有长期 ( 1992-01-01 to 2016-12-31) 温度数据的 NC 文件,我想将月平均温度和年平均温度提取R到一个空间 TIFF 文件中,这样我就可以在我拥有的 Excel 数据集中提取月平均温度数据,但是我有不知道怎么做。可以从这里访问数据。

如果有人可以帮助我编写将被应用的编码。

使用此代码,我尝试打开并查看数据:

library(ncdf4)
library(raster)
temp <- nc_open("dataset-ibi-reanalysis-phys-005-002-monthly_1547718004288.nc",write=TRUE)


TEMP = ncvar_get(temp,"bottomT")

latitude = ncvar_get(temp,"latitude")
longitude = ncvar_get(temp,"longitude")
nc_close(temp)

标签: rmappingextractionnetcattemperature

解决方案


如果您能够创建一个包含日期和温度列的 data.frame,类似于下面我的虚拟数据集,您可以轻松地使用 dplyr 和 lubridate 包来获取每月和每年的平均值。

使用 dplyr 的 mutate 函数将月份和年份列添加到 df 并润滑月份和年份函数

library(lubridate)
library(dplyr)
df <- data.frame(date = seq(from = ymd("2017-01-01"), to = ymd("2018-12-31"), length.out = 730),
                 temp = rnorm(n = 730, mean = 23, sd = 12))

使用 dplyr 的 mutate 函数和 lubridate 的月份和年份函数将月份和年份列添加到 df

df <- df %>% mutate(Month = month(date), Year = year(date))

df的前六行:

# date     temp         Month Year
# 2017-01-01 17.13885     1 2017
# 2017-01-02 34.23553     1 2017
# 2017-01-03 10.25110     1 2017
# 2017-01-04 11.19415     1 2017
# 2017-01-05 28.09097     1 2017
# 2017-01-06 17.58424     1 2017

您可以使用 dplyr 的 group_by 函数获取每月平均值,按月和年对 data.frame 进行分组,并使用 summarise 函数计算平均值。

monthly_summaries <- df %>% group_by(Year, Month) %>% 
  summarise(mean_temp = mean(temp))

这是monthly_summaries data.frame的前6行

#   Year Month mean_temp
#  2017     1      22.1
#  2017     2      24.6
#  2017     3      20.5
#  2017     4      25.7
#  2017     5      21.3
#  2017     6      23.4

同样,要获得年均值,使用 group_by 函数按年分组,并使用 summarise 函数计算年均值。

yearly_summaries <- df %>% group_by(Year) %>% 
  summarise(mean_temp = mean(temp))

这是年度摘要 data.frame:

#Year    mean_temp
#  2017      23.0
#  2018      23.1

(或者,如果您不想在 data.frame 中添加 Month 和 Year 列,则可以使用以下代码获得相同的输出:

monthly_summaries <- df %>% group_by(Year = year(date), Month = month(date)) %>% 
    summarise(mean = mean(temp))
yearly_summaries <- df %>% group_by(Month = month(date)) %>% 
    summarise(mean = mean(temp))

)


推荐阅读