Sumit
Sumit

Reputation: 2250

How to subtract one vector from another vector in r

I have a vector c <- c(1,2,3) and another vector d <- c(4,5,6,7). I want to subtract each element of c from each element of d to get a list of lists in R. How can I do so? Thanks.

Upvotes: 4

Views: 27593

Answers (3)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

outer does this if you're satisfied with a matrix instead of a list for your results:

a <- 1:3
b <- 4:7

outer(a, b, "-")
#      [,1] [,2] [,3] [,4]
# [1,]   -3   -4   -5   -6
# [2,]   -2   -3   -4   -5
# [3,]   -1   -2   -3   -4

Upvotes: 3

Julius Vainora
Julius Vainora

Reputation: 48201

x <- 1:3
y <- 4:7
lapply(x, `-`, y)
[[1]]
[1] -3 -4 -5 -6

[[2]]
[1] -2 -3 -4 -5

[[3]]
[1] -1 -2 -3 -4

Upvotes: 7

sgibb
sgibb

Reputation: 25726

a <- 1:3
b <- 4:6

a - b
# [1] -3 -3 -3

That is a basic question, please consider reading An Introduction to R.

EDIT:

a <- 1:3
b <- 4:7
lapply(a, function(x)x-b)
# [[1]]
# [1] -3 -4 -5 -6
# [[2]]
# [1] -2 -3 -4 -5
# [[3]]
# [1] -1 -2 -3 -4

Upvotes: 4

Related Questions