Search code examples
rdata-sciencegeospatialrastertiff

Problems Reading in TIF File In R


I'm trying to read in Tif files in R using raster. I basically need to match data from the tif file (coordinates) into specific boundaries of cities that I have as defined in another shapefile.
My TIF file is about 7 mb.

The issue is that the only way I know how to get these tif files into usable format is to first convert my RasterLayer into a dataframe. However when I try this, the dataframe ends up having about 300 million rows for some reason while the rasterlayer originally only had 16,000. This causes everything to stall. Im wondering if there is a simpler way to convert my TIF file into a readable format to R that I can then subsequently use in my Over function. My code is below. Any help would be appreciated.

city_lights <- raster(tif_file)
city_lights_df <- as.data.frame(city_lights, xy = TRUE)
coordinates(city_lights_df)<- ~x +y
proj4string(city_lights_df) <- proj4string(city_boundaries_poly_obj)

city_lights_coords <- over(city_lights_df, city_boundaries_poly_obj)

Solution

  • I'm not 100% clear from your question but I am assuming you want to return values from the raster where they are covered by your city boundaries polygon? If so try this, if not please provide more detail:

    city_lights <- raster(tif_file)
    city_lights <- crop(city_lights, city_boundaries_poly_obj)
    city_lights <- mask(city_lights, city_boundaries_poly_obj)
    res <- rasterToPoints(city_lights)