Skip to content
Back to formatted view

Raw Message

Message-ID: <CAM_vjumqnDDG=STEmVLByaQqX1LH3hKk9QaAyyb8xZVza3v-Rw@mail.gmail.com>
Date: 2012-12-05T18:42:01Z
From: Sarah Goslee
Subject: data manipulation between vector and matrix
In-Reply-To: <CAE2FW2m0pnEa6s7aDQL8THVjmLt714KZ+EbMQbv2odnbSemoyQ@mail.gmail.com>

Hi,

On Wed, Dec 5, 2012 at 1:30 PM, C W <tmrsg11 at gmail.com> wrote:
> Dear list,
> I was curious how to subtract a vector from matrix?
>
> Say, I have
>
> mat <- matrix(1:40, nrow=20, ncol=2)
>
> x <-c(1,2)

Thanks for the actual reproducible example.

> I want,
>
> x-mat[1,] and x-mat[2,], and so on... Basically, subtract column elements
> of x against column elements in mat.
>
> But x-mat won't do it.

This will (note the modification to get x - mat):
> sweep(-mat, 2, x, "+")
      [,1] [,2]
 [1,]    0  -19
 [2,]   -1  -20
 [3,]   -2  -21
 [4,]   -3  -22
 [5,]   -4  -23
etc.

--
Sarah Goslee
http://www.functionaldiversity.org