Create a factor with numeric interpretable factor levels.
Details
Some glmmTMB covariance structures require extra
information, such as temporal or spatial
coordinates. numFactor allows to associate such extra
information as part of a factor via the factor levels. The
original numeric coordinates are recoverable without loss of
precision using the function parseNumLevels. Factor levels
are sorted coordinate wise from left to right: first coordinate is
fastest running.
Examples
## 1D example
numFactor(sample(1:5,20,TRUE))
#> [1] (5) (1) (1) (5) (4) (2) (4) (3) (2) (5) (1) (2) (4) (3) (2) (5) (5) (2) (2)
#> [20] (4)
#> Levels: (1) (2) (3) (4) (5)
## 2D example
coords <- cbind( sample(1:5,20,TRUE), sample(1:5,20,TRUE) )
(f <- numFactor(coords))
#> [1] (5,3) (2,2) (1,1) (1,5) (1,1) (2,3) (3,4) (3,1) (2,1) (4,5) (2,4) (2,1)
#> [13] (1,3) (2,4) (5,3) (4,4) (5,1) (1,1) (2,1) (2,1)
#> 13 Levels: (1,1) (2,1) (3,1) (5,1) (2,2) (1,3) (2,3) (5,3) (2,4) ... (4,5)
parseNumLevels(levels(f)) ## Sorted
#> [,1] [,2]
#> [1,] 1 1
#> [2,] 2 1
#> [3,] 3 1
#> [4,] 5 1
#> [5,] 2 2
#> [6,] 1 3
#> [7,] 2 3
#> [8,] 5 3
#> [9,] 2 4
#> [10,] 3 4
#> [11,] 4 4
#> [12,] 1 5
#> [13,] 4 5
## Used as part of a model.matrix
model.matrix( ~f )
#> (Intercept) f(2,1) f(3,1) f(5,1) f(2,2) f(1,3) f(2,3) f(5,3) f(2,4) f(3,4)
#> 1 1 0 0 0 0 0 0 1 0 0
#> 2 1 0 0 0 1 0 0 0 0 0
#> 3 1 0 0 0 0 0 0 0 0 0
#> 4 1 0 0 0 0 0 0 0 0 0
#> 5 1 0 0 0 0 0 0 0 0 0
#> 6 1 0 0 0 0 0 1 0 0 0
#> 7 1 0 0 0 0 0 0 0 0 1
#> 8 1 0 1 0 0 0 0 0 0 0
#> 9 1 1 0 0 0 0 0 0 0 0
#> 10 1 0 0 0 0 0 0 0 0 0
#> 11 1 0 0 0 0 0 0 0 1 0
#> 12 1 1 0 0 0 0 0 0 0 0
#> 13 1 0 0 0 0 1 0 0 0 0
#> 14 1 0 0 0 0 0 0 0 1 0
#> 15 1 0 0 0 0 0 0 1 0 0
#> 16 1 0 0 0 0 0 0 0 0 0
#> 17 1 0 0 1 0 0 0 0 0 0
#> 18 1 0 0 0 0 0 0 0 0 0
#> 19 1 1 0 0 0 0 0 0 0 0
#> 20 1 1 0 0 0 0 0 0 0 0
#> f(4,4) f(1,5) f(4,5)
#> 1 0 0 0
#> 2 0 0 0
#> 3 0 0 0
#> 4 0 1 0
#> 5 0 0 0
#> 6 0 0 0
#> 7 0 0 0
#> 8 0 0 0
#> 9 0 0 0
#> 10 0 0 1
#> 11 0 0 0
#> 12 0 0 0
#> 13 0 0 0
#> 14 0 0 0
#> 15 0 0 0
#> 16 1 0 0
#> 17 0 0 0
#> 18 0 0 0
#> 19 0 0 0
#> 20 0 0 0
#> attr(,"assign")
#> [1] 0 1 1 1 1 1 1 1 1 1 1 1 1
#> attr(,"contrasts")
#> attr(,"contrasts")$f
#> [1] "contr.treatment"
#>
## parseNumLevels( colnames(model.matrix( ~f )) )
## Error: 'Failed to parse numeric levels: (Intercept)'
parseNumLevels( colnames(model.matrix( ~ f-1 )) )
#> [,1] [,2]
#> [1,] 1 1
#> [2,] 2 1
#> [3,] 3 1
#> [4,] 5 1
#> [5,] 2 2
#> [6,] 1 3
#> [7,] 2 3
#> [8,] 5 3
#> [9,] 2 4
#> [10,] 3 4
#> [11,] 4 4
#> [12,] 1 5
#> [13,] 4 5