showkey
showkey

Reputation: 298

How to get the differences of two set in R?

Suppose:

x <- c(2,-5)
y <- c(1,2,3)

How can I get :

z = c(2-1, 2-2, 2-3, -5-1, -5-2, -5-3) = c(1, 0, -1, -6, -7, -8)

Upvotes: 4

Views: 155

Answers (4)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193637

You can use rep as follows:

rep(x, each = length(y)) - y
# [1]  1  0 -1 -6 -7 -8

Upvotes: 9

CHP
CHP

Reputation: 17189

Adding answer for sake of adding alternative..

> x
[1]  2 -5
> y
[1] 1 2 3
> rowSums(expand.grid(-y,x))
[1]  1  0 -1 -6 -7 -8

Upvotes: 5

agstudy
agstudy

Reputation: 121588

In 2 steps (less elegant than @Ananda solution), using expand.grid

 d <- expand.grid(x,y)
 transform(d,difference = d$Var1 -d$Var2)
  Var1 Var2 difference
1    2    1          1
2   -5    1         -6
3    2    2          0
4   -5    2         -7
5    2    3         -1
6   -5    3         -8

But I think mine is more readable :) ( you know you substract what from what )

Upvotes: 4

Arun
Arun

Reputation: 118839

Using outer:

> as.vector(outer(x, y, '-'))
# [1]  1 -6  0 -7 -1 -8

And if you want the other way:

> as.vector(t(outer(x, y, '-')))
# [1]  1  0 -1 -6 -7 -8

Upvotes: 12

Related Questions