I have an R data frame as in the following example. I wish to calculate the differences in the column values between observations/ rows (all combinations).
my_df <- tibble(a=runif(5), b=runif(5), c=runif(5))
> my_df
# A tibble: 5 x 3
a b c
<dbl> <dbl> <dbl>
1 0.0513 0.267 0.846
2 0.614 0.683 0.937
3 0.230 0.700 0.0651
4 0.671 0.110 0.901
5 0.424 0.520 0.817
I have tried the code below which gives me only the difference between subsequent rows; I want to have all combinations: row2 - row1; row3 - row1; row4 - row1, row5- row1, row3 - row2, row4 - row2, and so on...
Also, the code I wrote does not seem the best to me (!), although it outputs the result I wish, but not for all possible combinations!
my_diff <- as.data.frame(diff(as.matrix(my_df)))
> my_diff
a b c
1 0.5623574 0.41522579 0.09165630
2 -0.3837289 0.01755953 -0.87209740
3 0.4407068 -0.58982681 0.83540813
4 -0.2463205 0.40943495 -0.08358985
I appreciate if someone could provide help in solving my question using R, if possible a using tidy verse options.
Thanks.