在对环境因子的数据进行分析时,大多数的全球环境因子数据都是栅格格式的数据, 并且按照时间序列或其他格式做成多个栅格数据集。 因此 需要对栅格数据集进行求平均值并转化为新的栅格数据集。
以worldclim网站的降水数据集为例(https://www.worldclim.org):
方法一:算总体的平均值
library(raster)
library(tidyverse)
#先设置输入和输出路径(输出路径可以自己设置。从电脑上复制下来的路径"\"要改成"/"。输入路径文件夹下只能有要分析的数据,不能存在其他的数据或者文件夹):
input="E:/AAAAA ml/ml/worldclim/wc2.1_30s_prec"
output="E:/AAAAA ml/ml/worldclim/precmean"
f <- list.files(input, full.names=T)
#worldclim上下载的数据集是.tif格式,如果从NCAR 上下载的数据集是.grib2格式,需要进行一步转换(以下#注释部分)
#a=stack(f)%>% calc(mean, filename=sub("\\.grib2", "mean.tif", output))
a=stack(f)%>% calc(mean, filename=sub("\\.tif", "mean.tif", output))
方法二:算月平均值/天平均值/小时平均值(以ncar下载的6h风30年重分析数据为例)
f <- list.files(input, full.names=T)
#years 和 months 可以自己修改
years=c(1980:2009)
months=c(1:12)
#如有需要对数据进行按月提取或按年提取,使用如下#注释部分
#yr <- substr(f, nchar(f)-11, nchar(f)-8) %>% as.integer()
#mo <- substr(f, nchar(f)-7, nchar(f)-6) %>% as.integer()
#f <- f[yr %in% years & mo %in% months]
outfile <- paste0(output, "/", basename(input))
outfile <- sub("grb2", "tif", outfile)
y <- f %>% lapply(stack)%>% Reduce("+", .)%>%"/"(24 * 365/12 * length(months) * length(years)) %>% writeRaster(outfile, overwrite=T)
###############################
处理好多个环境数据的图层后,进行堆叠并提取相应的点数据
library("sp")
library("spatstat")
library("maptools")
library("raster")
library("randomForest")
library("gdistance")
library("SDraw")
library("tidyverse")
crs.geo <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
#读入处理好的多个图层
arid= raster(choose.files())
proj4string(arid) <- crs.geo
prec = raster(choose.files())
proj4string(prec) <- crs.geo
env=stack(arid, prec)
names(env) [1] <- "arid"
names(env) [2] <- "prec"
cord= read.csv(choose.files(),header = T)
#将坐标数据集更改为 SpatialPoints 格式
locationsC <- SpatialPoints(cbind(cord$long ,cord$lat),
proj4string=crs.geo)
cord.UTM <- spTransform(locationsC, crs(env))
#提取成功
res <- extract(raster, cord.UTM, method='simple')
参考文献:
"A machine-learning approach to map landscape connectivity in Aedes aegypti with genetic and environmental data"
"Global wind patterns shape genetic differentiation, asymmetric gene flow, and genetic diversity in trees"
"Global wind patterns and the vulnerability of wind-dispersed species to climate change"