T. Zaborniak
T. Zaborniak

Reputation: 107

R: How can a dataframe with multiple values columns and (barely) irregular coordinates be converted into a RasterStack or RasterBrick?

I have been working with a dataframe in R which has coordinate columns (whose values are barely irregularly spaced, as I had to convert them to decimals from minute-second format from this set: http://www.arcgis.com/home/item.html?id=5771199a57cc4c29ad9791022acd7f74) and columns of values associated with each coordinate, as follows:

Latitude Longitude Elevation MAT MWMT MCMT   TD  MAP MSP AHM  SHM DD_0  DD5 DD_18 DD18 NFFD
54.99285 -129.9792        -2 6.8 14.4 -1.7 16.1 2473 696 6.8 20.6  283 1384  4100   30  246
54.99285 -129.9708        10 6.7 14.4 -1.8 16.1 2456 691 6.8 20.8  287 1383  4109   30  245
54.99285 -129.9625         5 6.8 14.4 -1.8 16.2 2431 686 6.9 21.0  286 1392  4097   31  246

# ... and so on.

From this, I am wanting to construct a RasterBrick of layers corresponding to each column. I initially thought that, with my dataframe being named 'clim_df':

clim_brick <- rasterFromXYZ(clim_df, crs = NA)

would be able to convert each of the columns to raster layers within a brick, but the following error was thrown (after I converted the latitude and longitude column names to 'y' and 'x'):

Error in rasterFromXYZ(clim_df) : x cell sizes are not regular

It seems as if, from https://www.rdocumentation.org/packages/raster/versions/2.6-7/topics/rasterFromXYZ that the coordinates must be evenly spaced for this function to work.

Would there be any way to remedy this issue? Any help would be appreciated.

P.S. I've used Stack Overflow before to figure things out, but never have asked a question directly. If I've not formatted things correctly, or am not providing enough information, let me know. Thanks!

Upvotes: 3

Views: 1155

Answers (1)

Cameron Bieganek
Cameron Bieganek

Reputation: 7704

You could try setting the digits argument to a lower number:

# Create a sample raster:
r <- raster(nrow = 10, ncol = 10, xmn = 0, xmx = 10, ymn = 0, ymx = 10, crs = NA)
r[] <- runif(100)
xyz <- rasterToPoints(r)

# Add a small amount of error to the coordinates:
xyz[, 1:2] <- xyz[, 1:2] + as.matrix(expand.grid(xerror = runif(10, -1e-4, 1e-4), yerror = runif(10, -1e-4, 1e-4)))

# Try to convert back to raster:
rasterFromXYZ(xyz)
# Error in rasterFromXYZ(xyz) : x cell sizes are not regular

# Try again with a lower value of `digits`:
rasterFromXYZ(xyz, digits = 3)
# class       : RasterLayer 
# dimensions  : 10, 10, 100  (nrow, ncol, ncell)
# resolution  : 0.9998915, 0.9998748  (x, y)
# extent      : -2.843587e-05, 9.998886, 0.001149737, 9.999898  (xmin, xmax, ymin, ymax)
# coord. ref. : NA 
# data source : in memory
# names       : layer 
# values      : 0.007020388, 0.9953495  (min, max)

Upvotes: 3

Related Questions