Search code examples
rrasterrasterize

character/factor equivalent of returned integer values from rasterize


When using raster::rasterize, I can feed a polygon attribute that is character for example state names. It converts the characters to integer values. How to find out what are the corresponding character/string for each integer value?

> rfc
class       : SpatialPolygonsDataFrame
features    : 23
extent      : -179.1332, 179.788, 13.23231, 71.39809  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=NAD83 +no_defs
variables   : 5
names       : SITE_ID, STATE,  RFC_NAME,  RFC_CITY, BASIN_ID
min values  :     ACR,    AK,    Alaska, Anchorage,    ABRFC
max values  :     TUA,    UT, West Gulf,     Tulsa,    WGRFC

which from that

> rfc$BASIN_ID
 [1] AKRFC MBRFC CBRFC ABRFC CNRFC LMRFC MARFC NCRFC NERFC NWRFC OHRFC SERFC
 [13] WGRFC WGRFC WGRFC WGRFC WGRFC WGRFC WGRFC WGRFC WGRFC WGRFC WGRFC
 13 Levels: ABRFC AKRFC CBRFC CNRFC LMRFC MARFC MBRFC NCRFC NERFC ... WGRFC

now if I use rasterize, it will return the following:

r
class       : RasterLayer
dimensions  : 3840, 4608, 17694720  (nrow, ncol, ncell)
resolution  : 1000, 1000  (x, y)
extent      : -2304000, 2304000, -1920001, 1919999  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=lcc +lat_1=30 +lat_2=60 +lat_0=40.0000076293945 +lon_0=-97 +x_0=0 +y_0=0 +a=6370000 +b=6370000 +units=m +no_defs
data source : in memory
names       : layer
values      : 1, 13  (min, max)

Solution

  • factors are represented internally as integers with character labels for each distinct number (level)

    As such

    levels(rfc$BASIN_ID)
    

    should return a character vector of length 13, which will correspond to the numbers 1,...13 present in the rasterLayer r.