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

This exercise is part of the course

Visualizing Geospatial Data in R

IntermediateSkill Level
4.4+
9 reviews

Learn to read, explore, and manipulate spatial data then use your skills to create informative maps using R.

In this chapter you'll follow the creation of a visualization from raw spatial data files to adding a credit to a map. Along the way, you'll learn how to read spatial data into R, more about projections and coordinate reference systems, how to add additional data to a spatial object, and some tips for polishing your maps.

Exercise 1: Reading in spatial dataExercise 2: Reading in a shapefileExercise 3: Reading in a raster file
Exercise 4: Getting data using a packageExercise 5: Coordinate reference systemsExercise 6: Merging data from different CRS/projectionsExercise 7: Converting from one CRS/projection to anotherExercise 8: Adding data to spatial objectsExercise 9: The wrong wayExercise 10: Checking data will matchExercise 11: Merging data attributesExercise 12: A first plotExercise 13: Polishing a mapExercise 14: Subsetting the neighborhoodsExercise 15: Adding neighborhood labelsExercise 16: Tidying up the legend and some final tweaksExercise 17: Wrap up

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free