Home > OS >  pairwise subtraction of columns in a dataframe in R
pairwise subtraction of columns in a dataframe in R

Time:11-11

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)

CodePudding user response:

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

CodePudding user response:

With combn:

dif <- combn(data[-1], 2, \(x) x[, 2] - x[, 1])
colnames(dif) <- combn(names(data)[-1], 2, \(x) paste(x[2], x[1], sep = "-"))

cbind(data, dif)
#  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
  • Related