I am trying to create a large (spatial?) dataframe for use in subsequent multivariate statistical analyses (e.g., PCA) from a set of 60 raster files.
I am somewhat new to working with spatial data in R and don't understand how spatial coordinate data is or is not retained or enforced in the data files.
I used the following code to read in a raster files and create a stack from them:
#load libraries
library(raster)
library(sp)
library(rgdal)
library(spatial.tools)
#set wd
setwd("C:/Users/...../data/")
#get raster files from wd
files <- list.raster.files(path = getwd(), pattern = ".tif$", recursive =FALSE, return_rasters = FALSE, return_bbox = FALSE)
#create rasterStack
mystack <- stack(files$raster_files)
#read metadata / summary of rasterStack
mystack
#output has "NA" for coordinate reference system.
Why did R lose the spaital reference info when I imported the files? When I look at the raster files in ArcGIS they definitely do have projection info.
I tried to manually apply the projection in this manner:
#first define the projection using the proj4 syntax
projection <- "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"
#then apply the projection to the rasterStack
projectRaster(files, projection, method = bilinear, filename = "STACKprj")
This gives me an error that the input data ("mystack") has NA as the refernece system, i.e., it can't work without having a starting reference system
#I try instead to apply the projection in this way:
STACKprj <- projection(mystack)
That doesn't work.
Any tips? Thank you!
You should try something like this:
library(raster)
library(sp)
library(rgdal)
#work wd
wd <- "C:/Users/...../data"
#get raster files from work wd
files <- list.raster.files(path = wd, pattern = ".tif$",
recursive =FALSE, return_rasters = FALSE, return_bbox = FALSE)
#create rasterStack
mystack <- stack(files$raster_files)
proj4string(mystack) <- CRS("+init=epsg:3857") # OSM Mercator projection