2

I have a CSV (value,lat,lon) that I am trying to create a raster grid from.

CSV File Sample:

temp,lat,lon
24.1,40.503,-69.248
21.7,38.461,-74.703
19.2,40.694,-72.048
18.5,41.443,-70.187
22.5,40.251,-73.164
14.3,44.287,-67.307
13.9,44.106,-68.109
20,40.369,-73.703

R Script:

library(raster)
library(rasterVis)

csv_path <- "file.csv"
csv_file <- paste(csv_path, sep="")
temp <- read.csv(csv_file) # takes a while
str(temp)
temp_coords <- cbind(temp$lon, temp$lat)
temp_pts <- SpatialPointsDataFrame(coords=temp_coords, 
data=data.frame(temp$temp))
names(temp_pts) <- "temp"

cell_size <- 0.75
lon_min <- -125.0; lon_max <- -65.0; lat_min <- 25.5; lat_max <- 50.5
ncols <- ((lon_max - lon_min)/cell_size)+1; nrows <- ((lat_max - lat_min)/cell_size)+1 
gridtemp <- raster(nrows=nrows, ncols=ncols, xmn=lon_min, xmx=lon_max, ymn=lat_min, ymx=lat_max, res=cell_size, crs="+proj=longlat +datum=WGS84")
gridtemp

us_fire <- rasterize(temp_coords, gridtemp, fun=mean)
us_fire

plot(us_fire, col=brewer.pal(9,"PuBuGn"), sub="CSV2RASTER")

Instead of displaying the correct values from the CSV file, it appears that the rasterizing converted the numbers to bogus values:

enter image description here

I need to create a raster with the correct values (column 1) from the CSV.

2
  • 2
    How is this bogus? Are the values expected to be in some range? Are you sure they are read incorrectly from the CSV? You've not given us the CSV, and not shown us a summary of the data read from the CSV, so there's not much we can do.
    – Spacedman
    Jan 10 '18 at 17:26
  • I provided a sample of data because the actual CSV file is 1,000+ lines long. Also, the original data provided in column 1 (temp) is much different ) from the output, which results in values in the 200s...
    – arnpry
    Jan 15 '18 at 10:32
6

In the rasterize step, you did not provide the values that want rasterized. Here is how you can do that:

library(raster)

# example data
temp <- read.csv(text="temp,lat,lon,
  24.1,40.503,-69.248,
  21.7,38.461,-74.703,
  19.2,40.694,-72.048,
  18.5,41.443,-70.187,
  22.5,40.251,-73.164,
  14.3,44.287,-67.307,
  13.9,44.106,-68.109,
  20,40.369,-73.703", header=TRUE)

# if these are points on a regular raster, you can do
# r <- rasterFromXYZ(temp[, c('lon', 'lat', 'temp')])

# in your case (no need to compute rows/colums):
x <- raster(xmn=-125, xmx=-65, ymn=25.5, ymx=50.5, res=0.75, crs="+proj=longlat +datum=WGS84")

us_fire <- rasterize(temp[, c('lon', 'lat')], x, temp[, 'temp'], fun=mean)
plot(us_fire)

Not the answer you're looking for? Browse other questions tagged or ask your own question.