Create a factor with numeric interpretable factor levels.
numFactor(x, ...)
parseNumLevels(levels)
Vector, matrix or data.frame that constitute the coordinates.
Additional vectors, matrices or data.frames that constitute the coordinates.
Character vector to parse into numeric values.
Factor with specialized coding of levels.
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.
## 1D example
numFactor(sample(1:5,20,TRUE))
#> [1] (3) (3) (5) (4) (3) (5) (1) (1) (5) (4) (2) (4) (3) (2) (5) (1) (2) (4) (3)
#> [20] (2)
#> 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,4) (5,5) (2,1) (2,2) (4,2) (5,3) (2,2) (1,1) (1,5) (1,1) (2,3) (3,4)
#> [13] (3,1) (2,1) (4,5) (2,4) (2,1) (1,3) (2,4) (5,3)
#> 14 Levels: (1,1) (2,1) (3,1) (2,2) (4,2) (1,3) (2,3) (5,3) (2,4) ... (5,5)
parseNumLevels(levels(f)) ## Sorted
#> [,1] [,2]
#> [1,] 1 1
#> [2,] 2 1
#> [3,] 3 1
#> [4,] 2 2
#> [5,] 4 2
#> [6,] 1 3
#> [7,] 2 3
#> [8,] 5 3
#> [9,] 2 4
#> [10,] 3 4
#> [11,] 5 4
#> [12,] 1 5
#> [13,] 4 5
#> [14,] 5 5
## Used as part of a model.matrix
model.matrix( ~f )
#> (Intercept) f(2,1) f(3,1) f(2,2) f(4,2) f(1,3) f(2,3) f(5,3) f(2,4) f(3,4)
#> 1 1 0 0 0 0 0 0 0 0 0
#> 2 1 0 0 0 0 0 0 0 0 0
#> 3 1 1 0 0 0 0 0 0 0 0
#> 4 1 0 0 1 0 0 0 0 0 0
#> 5 1 0 0 0 1 0 0 0 0 0
#> 6 1 0 0 0 0 0 0 1 0 0
#> 7 1 0 0 1 0 0 0 0 0 0
#> 8 1 0 0 0 0 0 0 0 0 0
#> 9 1 0 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 1 0 0 0
#> 12 1 0 0 0 0 0 0 0 0 1
#> 13 1 0 1 0 0 0 0 0 0 0
#> 14 1 1 0 0 0 0 0 0 0 0
#> 15 1 0 0 0 0 0 0 0 0 0
#> 16 1 0 0 0 0 0 0 0 1 0
#> 17 1 1 0 0 0 0 0 0 0 0
#> 18 1 0 0 0 0 1 0 0 0 0
#> 19 1 0 0 0 0 0 0 0 1 0
#> 20 1 0 0 0 0 0 0 1 0 0
#> f(5,4) f(1,5) f(4,5) f(5,5)
#> 1 1 0 0 0
#> 2 0 0 0 1
#> 3 0 0 0 0
#> 4 0 0 0 0
#> 5 0 0 0 0
#> 6 0 0 0 0
#> 7 0 0 0 0
#> 8 0 0 0 0
#> 9 0 1 0 0
#> 10 0 0 0 0
#> 11 0 0 0 0
#> 12 0 0 0 0
#> 13 0 0 0 0
#> 14 0 0 0 0
#> 15 0 0 1 0
#> 16 0 0 0 0
#> 17 0 0 0 0
#> 18 0 0 0 0
#> 19 0 0 0 0
#> 20 0 0 0 0
#> attr(,"assign")
#> [1] 0 1 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,] 2 2
#> [5,] 4 2
#> [6,] 1 3
#> [7,] 2 3
#> [8,] 5 3
#> [9,] 2 4
#> [10,] 3 4
#> [11,] 5 4
#> [12,] 1 5
#> [13,] 4 5
#> [14,] 5 5