Convert data.table to a RasterLayer for plotting, etc.

dt2raster(dt, r, val)

Arguments

dt

data.table object with columns ID, or both X and Y, and the values to assign to the raster specified by column val.

r

Raster* object.

val

The name of the column in dt containing the values for the raster.

Value

A RasterLayer object.

Author

Alex Chubaty

Examples

library(data.table)
library(sp)
library(raster)

r <- raster(nrows = 10, ncols = 10)
r[] <- 10

# using x,y coordinates
#dt1 <- data.table(X = , Y = , value = r[])

# using pixel ids
dt2 <- data.table(ID = 1L:ncell(r), VALUE = r[])
dt2[, VALUE := sample(1L:10L, ncell(r), replace = TRUE)]
#>         ID VALUE
#>      <int> <int>
#>   1:     1     5
#>   2:     2     3
#>   3:     3     4
#>   4:     4     4
#>   5:     5     2
#>   6:     6    10
#>   7:     7     7
#>   8:     8     8
#>   9:     9     6
#>  10:    10     3
#>  11:    11     7
#>  12:    12     8
#>  13:    13     3
#>  14:    14     8
#>  15:    15     7
#>  16:    16     3
#>  17:    17     4
#>  18:    18     2
#>  19:    19    10
#>  20:    20     6
#>  21:    21     9
#>  22:    22     1
#>  23:    23     2
#>  24:    24     1
#>  25:    25     2
#>  26:    26     8
#>  27:    27     6
#>  28:    28     7
#>  29:    29     7
#>  30:    30     1
#>  31:    31     6
#>  32:    32     2
#>  33:    33    10
#>  34:    34     5
#>  35:    35     9
#>  36:    36     9
#>  37:    37     7
#>  38:    38     1
#>  39:    39     7
#>  40:    40     9
#>  41:    41     7
#>  42:    42     3
#>  43:    43     1
#>  44:    44     5
#>  45:    45     8
#>  46:    46     9
#>  47:    47     3
#>  48:    48     6
#>  49:    49     9
#>  50:    50     4
#>  51:    51     9
#>  52:    52     1
#>  53:    53     4
#>  54:    54     3
#>  55:    55     5
#>  56:    56     2
#>  57:    57     2
#>  58:    58     7
#>  59:    59     9
#>  60:    60    10
#>  61:    61     1
#>  62:    62     2
#>  63:    63     1
#>  64:    64     6
#>  65:    65     3
#>  66:    66     4
#>  67:    67     6
#>  68:    68     5
#>  69:    69     2
#>  70:    70     1
#>  71:    71     9
#>  72:    72     6
#>  73:    73     4
#>  74:    74     2
#>  75:    75     6
#>  76:    76     7
#>  77:    77     1
#>  78:    78     5
#>  79:    79     9
#>  80:    80     5
#>  81:    81     1
#>  82:    82     1
#>  83:    83     3
#>  84:    84     4
#>  85:    85    10
#>  86:    86     7
#>  87:    87     4
#>  88:    88     7
#>  89:    89     8
#>  90:    90     8
#>  91:    91     7
#>  92:    92    10
#>  93:    93     2
#>  94:    94     6
#>  95:    95     8
#>  96:    96    10
#>  97:    97     5
#>  98:    98    10
#>  99:    99    10
#> 100:   100     9
#>         ID VALUE

if (interactive())
  plot(dt2raster(dt2, r, "VALUE"))