VolStudent
VolStudent

Reputation: 29

Subtract a single vector element from List of vectors

I have a list r containing n vectors of different length. And a separate vector a also of length n

x <- 1:100
r <- slider(x,.size=5)

a <- 1:length(r)

From every element in each vector of the list r I want to subtract an element of a. So the first element of a shall be subtracted from every element of the first vector of r.

Something like this, but on a larger scale and keeping the vectors in the list r

r[1]-a[1]
r[2]-a[2]
r[3]-a[3]

This gives me Error in r[1] - n[1] : non-numeric argument to binary operator

Disclaimer: The vectors of r in the example do NOT have different lengths. I do not know how to do this when generating the example.

Upvotes: 0

Views: 485

Answers (3)

akrun
akrun

Reputation: 887028

We could use a for loop

out <- vector('list', length(r))
for(i in seq_along(r)) {
       out[[i]] <- r[[i]] - a[i]
}

Upvotes: 0

Duck
Duck

Reputation: 39595

Same result from @RonakShah can be obtained with:

mapply(`-`,r,a)

Output:

[[1]]
[1] 0 1 2 3 4 5 6 7

[[2]]
[1] -1  0  1  2  3  4  5  6  7

[[3]]
 [1] -2 -1  0  1  2  3  4  5  6  7

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388862

You can use Map :

Map(`-`, r, a)

Upvotes: 3

Related Questions