Reputation: 11
I have a matrix defined as the pair-wise differences between the elements of an array:
a <- as.matrix(dist(c(1,2,3,4,5)))
I need to compute without looping the sum of the pair-wise differences between the first two elements, the first three elements, etc. i.e., I need to arrive to the array:
v <- c(1,4,10,20)
Upvotes: 1
Views: 507
Reputation: 28632
I don't know if you indeed want the to call the cumulative sum function twice, as I think "the sum of the pair-wise differences between the first two elements, the first three elements, etc." should result in:
c(1, 3, 6, 10)
Anyway, this should work with non-sequential x
as well for your required output:
> cumsumdiff <- function (x) cumsum(cumsum(sapply(x[-1], `-`, x[1])))
> cumsumdiff(1:5)
[1] 1 4 10 20
Or based on @Jota's suggestion using the distance matrix:
> cumsumdiff <- function(x) cumsum(cumsum(unname(as.matrix(dist(x))[1, -1])))
> cumsumdiff(1:5)
[1] 1 4 10 20
Upvotes: 2