# Calculating the difference of all variables to all other variables

Suppose my Dataframe look like:

``````w <- sample(-10:10, size =10)
x <- sample(-10:10, size =10)
y <- sample(-10:10, size =10)
z <- sample(-10:10, size =10)
df <- data.frame(w,x,y,z)
``````

Now I want to calculate the amout of the difference (|w-x|) of each column to all the others.So I want it like the example down but additionally also wie the columns w_z, and x_y, y_z, y_z ….(my orignial df have some more Variables)

``````df\$w_x <- abs(df\$w-df\$x)
df\$w_y <- abs(df\$w-df\$x)
``````

Alternativly, if there are easyer solution, its ok to have the calculation to a new df / matrix. Thanks in advance.

### >Solution :

Here is a method with `combn`

``````nm1 <- combn(names(df), 2, FUN = paste, collapse = "_")
df[nm1] <- combn(df, 2, FUN = function(x) abs(x[]- x[]))
``````

-output

``````> df
w  x  y   z w_x w_y w_z x_y x_z y_z
1    7  3 -2   6   4   9   1   5   3   8
2   -6  6  7   0  12  13   6   1   6   7
3   -8  0 -7   8   8   1  16   7   8  15
4    9 -9 -4  -2  18  13  11   5   7   2
5    5 -3  5  -4   8   0   9   8   1   9
6    2 -6 -8 -10   8  10  12   2   4   2
7   -5  7  2  -9  12   7   4   5  16  11
8    3 -2  4  -6   5   1   9   6   4  10
9  -10 -4  9   9   6  19  19  13  13   0
10   8  5 10   4   3   2   4   5   1   6
``````