Home > Software engineering >  Difference between two variables in R within the same group
Difference between two variables in R within the same group

Time:10-16

I have a dataset with the following structure:

enter image description here

I would like to make the difference between two variables in the same group. Thus, the result I wish to obtain is the following:

enter image description here

Note that the difference must always be equal to or bigger than 0. I would like to solve it using R.

CodePudding user response:

Try group by and diff function.

library(tidyverse)

df <- data.frame(group = rep(LETTERS[1:3], each=2),
                 value = c(20, 5, 0, 30, 10, 2))

df %>% 
    group_by(group) %>% 
    summarise(difference= abs(diff(value)))

# A tibble: 3 × 2
  group difference
  <chr>      <dbl>
1 A            15
2 B            30
3 C             8
  • Related