[S] Q: subtracting a constant from each col of a matrix

Joe Davis (jdavis@spdc.ti.com)
Wed, 18 Mar 1998 08:48:18 -0600

In general, Splus' matrix operations do the right thing. If I want to multiply
a matrix by a constant, then nX <- a*X works. However, I often want to
subtract a different constant from each col. of a matrix ( the vector of
being a nominal value of some sort and the matrix being the predictions of
some sort).

a <- c(1,2,3)
X <- cbind(c(1,1,1),c(2,2,2),c(3,3,3))

The way that I have been doing this is to create my 'diff' matrix:

b <- matrix(a,nrow=ncol(X),ncol=length(a), byrow=T)

d1 <- b - X
> d1
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0

which is what I want.

My question is "is there a better way to do this?"

I have tried apply(X,1,diff,a), but I get many warnings and not the
right answer. It seems to me that this should also work, but it does
not appear to.

> apply(X,1,diff,a)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
There were 9 warnings (use warnings() to see them)

Does anyone out there have a better solution?



     Joseph C. Davis               Texas Instruments, Inc
  Process Flow Synthesis          P.O. Box 655012, MS 3704
     (972) 927-3805                   Dallas, TX 75265
This message was distributed by s-news@wubios.wustl.edu.  To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message:  unsubscribe s-news