Search code examples
rdataframeloopsdplyrapply

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

  • 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