Find the difference between all the values ​​of the two vectors

I am trying to find the difference between many pairs of numbers.

These numbers are in two vectors of unequal length. For instance,

    a<- c(1:5)
    b<- c(1:10)

Now I need some way to calculate a [[1]] - b, and then a [[2]] - b, etc. until [[5]] - b. Each of these calculations should lead to a vector 10 characters long.

Each of these difference vectors must be stored together as columns in a data frame. The first column should be the subtracted position “b”, and the subsequent columns should have the name “a” (therefore, there are 5 columns and 10 rows).

         a[1] a[2] ... a[5]
    b[1]
    b[2]
    ...
    b[10]

R. *. , , , . !

P.S. , . , .

+4
2
sapply(a, "-", b)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    2    3    4
# [2,]   -1    0    1    2    3
# [3,]   -2   -1    0    1    2
# [4,]   -3   -2   -1    0    1
# [5,]   -4   -3   -2   -1    0
# [6,]   -5   -4   -3   -2   -1
# [7,]   -6   -5   -4   -3   -2
# [8,]   -7   -6   -5   -4   -3
# [9,]   -8   -7   -6   -5   -4
#[10,]   -9   -8   -7   -6   -5

, R , - a b.

+3

outer:

t(outer(a, b, '-'))

     # [,1] [,2] [,3] [,4] [,5]
 # [1,]    0    1    2    3    4
 # [2,]   -1    0    1    2    3
 # [3,]   -2   -1    0    1    2
 # [4,]   -3   -2   -1    0    1
 # [5,]   -4   -3   -2   -1    0
 # [6,]   -5   -4   -3   -2   -1
 # [7,]   -6   -5   -4   -3   -2
 # [8,]   -7   -6   -5   -4   -3
 # [9,]   -8   -7   -6   -5   -4
# [10,]   -9   -8   -7   -6   -5
+5

Source: https://habr.com/ru/post/1692634/


All Articles