Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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[[1]]- x[[2]]))

-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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading