Weighted Matrix Crossproduct
wcrossprod.RdGiven matrices x and y as arguments and an optional matrix or vector of weights, w,
return a weighted matrix cross-product, t(x) w y.
If no weights are supplied, or the weights are constant, the function uses
crossprod for speed.
Author
Michael Friendly, John Fox jfox@mcmaster.ca
Examples
set.seed(12345)
n <- 24
drop <- 4
sex <- sample(c("M", "F"), n, replace=TRUE)
x1 <- 1:n
x2 <- sample(1:n)
extra <- c( rep(0, n - drop), floor(15 + 10 * rnorm(drop)) )
y1 <- x1 + 3*x2 + 6*(sex=="M") + floor(10 * rnorm(n)) + extra
y2 <- x1 - 2*x2 - 8*(sex=="M") + floor(10 * rnorm(n)) + extra
# assign non-zero weights to 'dropped' obs
wt <- c(rep(1, n-drop), rep(.2,drop))
X <- cbind(x1, x2)
Y <- cbind(y1, y2)
wcrossprod(X)
#> x1 x2
#> x1 4900 4145
#> x2 4145 4900
wcrossprod(X, w=wt)
#> x1 x2
#> x1 3276.0 2970.6
#> x2 2970.6 3935.2
wcrossprod(X, Y)
#> y1 y2
#> x1 20553 -748
#> x2 20955 -4169
wcrossprod(X, Y, w=wt)
#> y1 y2
#> x1 13263.4 -2058.4
#> x2 15180.6 -5167.4
wcrossprod(x1, y1)
#> [,1]
#> [1,] 20553
wcrossprod(x1, y1, w=wt)
#> [,1]
#> [1,] 13263.4