I have a sample .csv file (sample download) that I am trying to convert to a gridded raster. So far, I have used two methods, one of the methods is explained in the answer here. But, I am running into problems, how can I fix this problem in R? The code for the first method is as follows:
# CSV to raster
library(raster)
# sample data
sample <- read.csv("Sample_Data.csv", header=TRUE)
x <- raster(xmn=-110.906, xmx=-110.031, ymn=43.03938, ymx=44.3438, res=0.0625, crs="+proj=longlat +datum=WGS84")
rstr <- rasterize(sample[, c('X', 'Y')], x, sample[, 'VIC_SC_04'])
plot(rstr)
This code results the plot nelow and as you can see it's not gridded.
So I tried another method, and the code for this method is:
# CSV to raster
library(raster)
library(sp)
library(rgdal)
library(rgeos)
# sample data
sample <- read.csv("Sample_Data.csv", header=TRUE)
data<-data.frame(sample$X,sample$Y,sample$VIC_SC_04)
# points from scratch
coords = cbind(sample$X,sample$Y)
sp = SpatialPoints(coords)
# make spatial data frame
spdf = SpatialPointsDataFrame(sp, data)
spdf_pi = SpatialPixelsDataFrame(sp,tolerance = 0.016129, data) # Storing incorrect values in Z basically storing X coordinates in z as well**
raster = raster(spdf_pi[data$VIC_SC_04]) # gives error Error in which(sapply(from@data, is.factor)) :
argument to 'which' is not logical
# back to data
as.data.frame(data)
plot(data)
# Another try
dfr <- rasterFromXYZ(data) #Convert first two columns as lon-lat and third as value (throws an error)
plot(dfr)
# coerce to SpatialPixelsDataFrame
gridded(spdf_pi) <- TRUE
# coerce to raster
rasterDF <- raster(spdf_pi)
plot(rasterDF)
When I plot 'data', I get:
plot(data)
But in the following line, I get the following respective error:
dfr <- rasterFromXYZ(data)
Error in rasterFromXYZ(data) : x cell sizes are not regular
fun=mean
inside therasterize()
. You received the second error message because x, y pair has to be on the regular grid when usingrasterFromXYZ()
.