I am new to R. I am working on cmip6 models. I have over 200 plus .nc files. I can run the script for individual files and get the output i need but having hard time looping the script. Can you guys help me out. It will save me alot of my time. Thank you in advance.
setwd("D:\\data")
library (raster) ## load required library
library(sp) ## load library
library(ncdf4)
station.data = read.csv(file.choose(), sep = ",", header =T) ## import station data.file
lon.lat = station.data[,c(2,3)] ## extract data of all stations in station file for which point values are to be extractd
lon.lat = SpatialPoints(lon.lat) ## lon.lat for further use
lon.lat
robject = brick(file.choose(), varname = "pr")## import raster netcdf file from which point values are to be extractd
dim(robject) ## check the dimensions of project
vall = extract(robject , lon.lat, method = "simple" ) ## extract values
vall = t(vall)
write.csv(vall, file = "earthvegbil.csv", fileEncoding = "macroman") ## save output csv file containing extracted point values .
CodePudding user response:
Put your code in an lapply
and loop over the indeces of your files. The latter is useful to get nice numerical suffixes in write.csv
.
setwd("D:\\data")
files <- list.files(pattern=".csv$")
bricks <- list.files(pattern=".pr$")
stopifnot(length(files) == length(bricks)) ## check for equal length of both vectors
mapply(seq_along(files), \(x) {
station.data <- read.csv(files[[x]], sep=", ", header=T) ## import station data.file
lon.lat <- station.data[, c(2, 3)] ## extract data of all stations in station file for which point values are to be extractd
lon.lat <- SpatialPoints(lon.lat) ## lon.lat for further use
robject <- brick(bricks[[x]], varname="pr")## import raster netcdf file from which point values are to be extractd
vall <- extract(robject , lon.lat, method="simple" ) ## extract values
vall <- t(vall)
write.csv(vall, file=sprintf('./out/earthvegbil_d.csv', x), fileEncoding="macroman") ## save output csv file containing extracted point values .
}