Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between two variables in R within the same group

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading