This function creates a vector, matrix or array of constants, typically used for the unit vector or unit matrix in matrix expressions.
Details
The "dimnames"
attribute is optional: if present it is a list with one component for each dimension,
either NULL
or a character vector of the length given by the element of the "dim"
attribute for that
dimension. The list can be named, and the list names will be used as names for the dimensions.
Examples
J(3)
#> [1] 1 1 1
J(2,3)
#> [,1] [,2] [,3]
#> [1,] 1 1 1
#> [2,] 1 1 1
J(2,3,2)
#> , , 1
#>
#> [,1] [,2] [,3]
#> [1,] 1 1 1
#> [2,] 1 1 1
#>
#> , , 2
#>
#> [,1] [,2] [,3]
#> [1,] 1 1 1
#> [2,] 1 1 1
#>
J(2,3, constant=2, dimnames=list(letters[1:2], LETTERS[1:3]))
#> A B C
#> a 2 2 2
#> b 2 2 2
X <- matrix(1:6, nrow=2, ncol=3)
dimnames(X) <- list(sex=c("M", "F"), day=c("Mon", "Wed", "Fri"))
J(2) %*% X # column sums
#> day
#> Mon Wed Fri
#> [1,] 3 7 11
X %*% J(3) # row sums
#>
#> sex [,1]
#> M 9
#> F 12