[R] need help in understanding R code, and maybe some math

Douglas Bates bates at stat.wisc.edu
Sun May 23 13:58:35 CEST 2010

On Sun, May 23, 2010 at 5:09 AM, Peter Ehlers <ehlers at ucalgary.ca> wrote:
> On 2010-05-23 0:56, john smith wrote:
>> Hi,
>> I am trying to implement Higham's algorithm for correcting a non positive
>> definite covariance matrix.
>> I found this code in R:
>> http://projects.cs.kent.ac.uk/projects/cxxr/trac/browser/trunk/src/library/Recommended/Matrix/R/nearPD.R?rev=637
>> I managed to understand most of it, the only line I really don't
>> understand
>> is this one:
>> X<- tcrossprod(Q * rep(d[p], each=nrow(Q)), Q)
>> This line is supposed to calculate the matrix product Q*D*Q^T, Q is an n
>> by
>> m matrix and R is a diagonal n by n matrix. What does this mean?
>> I also don't understand the meaning of a cross product between matrices, I
>> only know it between vectors.

In the original S language, on which R is based, the function named
crossprod was used for what statisticians view as the cross-product of
the columns of a matrix, such as a multivariate data matrix or a model
matrix.  That is

crossprod(X) := X'X

This is a special case of the cross-product of the columns of two
matrices with the same number of rows

crossprod(X, Y) := X'Y

The tcrossprod function was introduced more recently to mean the
crossprod of the transpose of X.  That is

trcossprod(X) := crossprod(t(X)) := X %*% t(X)

These definitions are unrelated to the cross-product of vectors used
in Physics and related disciplines.

The reason for creating such functions is that these are common
operations in statistical computing and it helps to know the special
structure (e.g. the result of crossprod(X) or tcrossprod(X) is a
symmetric, positive semidefinite matrix).

> You could have a look at the help page for crossprod which
> gives the definitions of crossprod and tcrossprod.
> Perhaps this will help:
> Q <- matrix(1:12, ncol=3)
> v <- rep(1:3, each=nrow(Q)
> Q
> v
> Q * v
> (Q * v) %*% t(Q)
> tcrossprod(Q * v, Q)
>  -Peter Ehlers
>> Thanks,
>> Barisdad.
>>        [[alternative HTML version deleted]]
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list