This repository has been archived by the owner on Jun 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vars.R
46 lines (35 loc) · 1.4 KB
/
Vars.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#! /usr/bin/Rscript
## Script to extract climatic data from rasters
## raster files (.asc) must be provided by the user on a directory named "rasters" on working directory
## Guillermo Huerta Ramos
# start with a new environment
rm(list = ls())
# load libraries
library('raster')
# load raster files
rasters<- list.files("./data/data_in/rasters",pattern='asc', full.names=TRUE )
# stack vectors to concatenate multiple vectors into a single vector along with a factor indicating where each observation originated.
print(paste0("stacking vectors to create predictors variable"))
predictors<-stack(rasters)
# get file names from input data to use for the loop
file.names <- dir("./data/data_out/rarf")
# this directory will contain csv files with final data
dir.create("./data/data_out/vars")
# set working directory
setwd("./data/data_out/vars")
for(i in file.names){
setwd("../rarf")
print(paste0("reading ", i, " records"))
# read record file
vars <- read.table(i, header = T, sep = ",",stringsAsFactors = F, row.names = "X")
# subset geographic coordinates only
vars<-subset(vars, select=c(lon,lat))
# extract climatic data from each record based on raster files
print(paste0("extracting climatic data from rasters"))
presvals <- extract(predictors, vars)
setwd("../vars")
# write new file with final data
print(paste0("writing climatic variables file for ", i))
write.csv(presvals,i)
}
print(paste0("Job finished"))