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

pairwise subtraction of columns in a dataframe in R

I was wondering is there a way to automate (e.g., loop) the subtraction of (X2-X1), (X3-X1), (X3-X2) in my data below and add them as three new columns to the data?

m="
id X1 X2 X3
A  1  0  4
B  2  2  2
C  3  4  1"

data <- read.table(text = m, h = T)

>Solution :

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

This is very similar to this question; we basically just need to change the function that we are using in map2_dfc:

library(tidyverse)

combn(names(data)[-1], 2) %>% 
  map2_dfc(.x = .[1,], .y = .[2,], 
           .f = ~transmute(data, !!paste0(.y, "-", .x) := !!sym(.y) - !!sym(.x))) %>% 
  bind_cols(data, .)

#>   id X1 X2 X3 X2-X1 X3-X1 X3-X2
#> 1  A  1  0  4    -1     3     4
#> 2  B  2  2  2     0     0     0
#> 3  C  3  4  1     1    -2    -3
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