Get Started

Reading in a raster file

Raster files are most easily read in to R with the raster() function from the raster package. You simply pass in the filename (including the extension) of the raster as the first argument, x.

The raster() function uses some native raster package functions for reading in certain file types (based on the extension in the file name) and otherwise hands the reading of the file on to readGDAL() from the rgdal package. The benefit of not using readGDAL() directly is simply that raster() returns a RasterLayer object.

A common kind of raster file is the GeoTIFF, with file extension .tif or .tiff. We've downloaded a median income raster from the US census and put it in your working directory.

Let's take a look and read it in.

This is a part of the course

“Visualizing Geospatial Data in R”

View Course

Exercise instructions

  • Use dir() to take a look in your working directory.
  • Use dir() again to look inside the directory nyc_grid_data.
  • Use raster() to read in the median income raster to the variable income_grid by passing in the complete path to the .tif file.
  • Use summary() to verify the raster is stored in a RasterLayer.
  • Use plot() to verify the raster's contents.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

library(raster) 

# Call dir()


# Call dir() on the directory


# Use raster() with file path: income_grid


# Call summary() on income_grid


# Call plot() on income_grid
Edit and Run Code