# How to find the absolute difference between all pairs of rows?

I have a df of 10 rows and would like to find the absolute difference abs() between all pairs of rows as a matrix.

``````id  rate
1   33.1
2   12.4
3   15.3
4   16
5   23.1
6   14.5
7   26.6
8   18.6
9   17
10  25.2
``````

Is this what you are looking for?

````````` r
DF <- data.frame(rate = c(33.1, 12.4, 15.3, 16, 23.1, 14.5, 26.6, 18.6, 17, 25.2))
VecList <- vector(mode = "list", length = 9)
for ( i in 1:9) {
VecList[[i]] <- c(rep(NA, i), DF[1:(10 - i), "rate"])
}
VecList
#> [[1]]
#>  [1]   NA 33.1 12.4 15.3 16.0 23.1 14.5 26.6 18.6 17.0
#>
#> [[2]]
#>  [1]   NA   NA 33.1 12.4 15.3 16.0 23.1 14.5 26.6 18.6
#>
#> [[3]]
#>  [1]   NA   NA   NA 33.1 12.4 15.3 16.0 23.1 14.5 26.6
#>
#> [[4]]
#>  [1]   NA   NA   NA   NA 33.1 12.4 15.3 16.0 23.1 14.5
#>
#> [[5]]
#>  [1]   NA   NA   NA   NA   NA 33.1 12.4 15.3 16.0 23.1
#>
#> [[6]]
#>  [1]   NA   NA   NA   NA   NA   NA 33.1 12.4 15.3 16.0
#>
#> [[7]]
#>  [1]   NA   NA   NA   NA   NA   NA   NA 33.1 12.4 15.3
#>
#> [[8]]
#>  [1]   NA   NA   NA   NA   NA   NA   NA   NA 33.1 12.4
#>
#> [[9]]
#>  [1]   NA   NA   NA   NA   NA   NA   NA   NA   NA 33.1
sapply(VecList, FUN = function(x) abs(x - DF\$rate))
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#>  [1,]   NA   NA   NA   NA   NA   NA   NA   NA   NA
#>  [2,] 20.7   NA   NA   NA   NA   NA   NA   NA   NA
#>  [3,]  2.9 17.8   NA   NA   NA   NA   NA   NA   NA
#>  [4,]  0.7  3.6 17.1   NA   NA   NA   NA   NA   NA
#>  [5,]  7.1  7.8 10.7 10.0   NA   NA   NA   NA   NA
#>  [6,]  8.6  1.5  0.8  2.1 18.6   NA   NA   NA   NA
#>  [7,] 12.1  3.5 10.6 11.3 14.2  6.5   NA   NA   NA
#>  [8,]  8.0  4.1  4.5  2.6  3.3  6.2 14.5   NA   NA
#>  [9,]  1.6  9.6  2.5  6.1  1.0  1.7  4.6 16.1   NA
#> [10,]  8.2  6.6  1.4 10.7  2.1  9.2  9.9 12.8  7.9
``````

Created on 2021-03-06 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.