# Finding distance between raster pixels and line features in R

I have a raster file and a SpatialLinesDataFrame in R. I need to find the distance between each pixel (at the center) and the nearest point in the line file. I believe this is the functional equivalent of the "near" function in ArcGIS. Is there a package or function that does this in R?

The raster is of a landscape with the year of deforestation as the cell value. The lines file is a series of roads- 34 total. I'm trying to determine the probability of deforestation around the roads using the distance of a point from the road as a variable.

The raster structure is:

``````# class       : RasterLayer
# dimensions  : 9003, 7906, 71177718  (nrow, ncol, ncell)
# resolution  : 0.00025, 0.00025  (x, y)
# extent      : -52.7825, -50.806, -1.125, 1.12575  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
# data source : U:\Jacy\Research\TS_line_analysis\GIS_Project\NE_Hansen
# names       : NE_Hansen
# values      : 0, 14  (min, max)
``````
• What is the extent of your lines data? Are there any missing data values in the raster? – Spacedman Mar 30 '17 at 6:55
• @spacedman, the line extent is extent(ts_line) # class : Extent # xmin : -52.51523 # xmax : -51.07509 # ymin : -0.8724459 # ymax : 0.8546136 The raster file is a buffer around the lines (30km either way), so they overlap completely. There are a substantial number of NA values in my raster. I could give them a value without messing up my analysis if that will help. Thank you! – Jace Mar 30 '17 at 18:28

Convert the raster to points, and use `gDistance`:

Some test data - some lines I had already and a raster over the lines:

``````> plot(lines)
> r = raster(extent(lines),100,100)
``````

Convert to points:

``````> p = as(r,"SpatialPoints")
``````

Use `rgeos` for distance calcs:

``````> require(rgeos)
> d = gDistance(p, lines, byid=TRUE)
Warning messages:
1: In RGEOSDistanceFunc(spgeom1, spgeom2, byid, "rgeos_distance") :
Spatial object 2 is not projected; GEOS expects planar coordinates
2: In RGEOSDistanceFunc(spgeom1, spgeom2, byid, "rgeos_distance") :
spgeom1 and spgeom2 have different proj4 strings
``````

Ignore warning messages unless your data really has different projections. Resulting distances are in a matrix, because I have 3 lines and 100*100 points, I'm getting the nearest distance from the points to each of my three lines:

``````> dim(d)
     3 10000
``````

If you have a lot of lines then merge them down to a single feature.

Find the minimum point-to-line distance:

``````> dmin = apply(d,2,min)
``````

``````> r[]=dmin 