[R] is there a way to let R do smart matrix-vector operation?
Marc Schwartz (via MN)
mschwartz at mn.rr.com
Tue Mar 7 00:20:12 CET 2006
On Mon, 2006-03-06 at 15:10 -0800, Michael wrote:
> Hi all,
>
> I want to substract vector B from A's each column... how can R do that
> smartly without a loop?
>
> > A=matrix(c(2:7), 2, 3)
> > A
> [,1] [,2] [,3]
> [1,] 2 4 6
> [2,] 3 5 7
> > B=matrix(c(1, 2), 2, 1)
> > B
> [,1]
> [1,] 1
> [2,] 2
> > A-B
> Error in A - B : non-conformable arrays
> apply(A, 2, "-", B)
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 1 3 5
You can use apply() on column-wise operations such as this.
See ?apply for more information.
HTH,
Marc Schwartz
More information about the R-help
mailing list