Subtract a single vector element from List of vectors

373 views Asked by At

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.

3

There are 3 answers

0
Ronak Shah On BEST ANSWER

You can use Map :

Map(`-`, r, a)
0
akrun On

We could use a for loop

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

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