Skip to contents

A fast data.table-based alternative to raster::crosstab().

Usage

crosstabDT(x, y, digits = 0, long = FALSE, useNA = FALSE)

Arguments

x

A Raster* object

y

If x has just one layer, a RasterLayer object. Otherwise, if x is a multi-layered RasterStack or RasterBrick, this argument (if any) is unused.

digits

Integer. The number of digits for rounding the values before cross-tabulation. Default is 0.

long

Logical. If TRUE, the results are returned in a 'long' format data.table instead of as a table. Default is FALSE.

useNA

Logical. Should the returned table or data.table include counts of NA values? Default is FALSE.

Value

Either a table or a data.table recording the frequency of each combination of raster values.

Author

Joshua O'Brien

Examples

r <- raster(nc = 5, nr = 5)
r[] <- runif(ncell(r)) * 2
s <- setValues(r, runif(ncell(r)) * 3)
crosstabDT(r, s)
#>    y
#> x   0 1 2 3
#>   0 1 5 1 1
#>   1 2 3 4 4
#>   2 1 1 1 1

rs <- r/s
r[1:5] <- NA
s[20:25] <- NA
x <- stack(r, s, rs)
crosstabDT(x, useNA = TRUE, long = TRUE)
#>     layer.1 layer.2 layer.3 Freq
#>  1:      NA       0       3    1
#>  2:      NA       1       0    1
#>  3:      NA       2       1    1
#>  4:      NA       3       0    1
#>  5:      NA       3       1    1
#>  6:       0      NA       0    2
#>  7:       0      NA       1    1
#>  8:       0       1       0    1
#>  9:       0       1       1    1
#> 10:       0       2       0    1
#> 11:       0       3       0    1
#> 12:       1      NA       0    1
#> 13:       1      NA       1    1
#> 14:       1      NA       2    1
#> 15:       1       1       1    2
#> 16:       1       2       0    2
#> 17:       1       2       1    1
#> 18:       1       3       0    2
#> 19:       2       0      22    1
#> 20:       2       1       1    1
#> 21:       2       2       1    1
#>     layer.1 layer.2 layer.3 Freq