SDahm
SDahm

Reputation: 436

dplyr solution: absolute difference of two values in one column matched by other column

I have a dataframe that looks like this, but there will be many more IDs:

# Groups:   ID [1]
      ID   ARS stim 
   <int> <int> <chr>
 1     3     0 1    
 2     3     4 2    
 3     3     2 3    
 4     3     3 4    
 5     3     1 5    
 6     3     0 6    
 7     3     2 10   
 8     3     4 11   
 9     3     0 12   
10     3     3 13   
11     3     2 14   
12     3     2 15   

I would like to calculate the sum of the absolute difference abs() between the values in ARS, e.g. for stim=1 and stim=10 plus for stim=2 and stim=11 and so on. Any good solutions are appreciated!

The desired output calculation is:

abs(0-2) + abs(4-4) + abs(2-0) + abs(3-3) + abs(1-2) + abs(0-2)

Hence, 2+0+2+0+1+2 Output for ID==3: 7

Upvotes: 2

Views: 588

Answers (1)

PaulS
PaulS

Reputation: 25333

A possible solution:

library(dplyr)

df <- structure(list(ID = c(3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), ARS = c(0, 4, 2, 3, 1, 0, 2, 4, 0, 3, 2, 2), stim = c(1, 2, 3, 4, 5, 6, 
                                                                                                                    10, 11, 12, 13, 14, 15)), row.names = c(NA, -12L), class = "data.frame")

df %>% 
  group_by(ID) %>% 
  summarise(value = abs(ARS[which(stim == 1:6)] - ARS[which(stim == 9+1:6)]),
            .groups = "drop") %>% 
  pull(value) %>% sum

#> [1] 7

Upvotes: 1

Related Questions