Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tidyverse column-wise differences

Suppose I have a data frame like this:

df = data.frame(preA = c(1,2,3),preB = c(3,4,5),postA = c(6,7,8),postB = c(9,8,4))

I want to add columns having column-wise differences, that is:

diffA = postA - preA
diffB = postB - preB 

and so on...
Is there an efficient way to do this in tidyverse?

like image 318
Ravi Avatar asked Sep 03 '25 06:09

Ravi


1 Answers

You can do this with two uses of across(), creating new variables with the first use and subtracting the second. This also assumes your columns are in order.

df %>%
  mutate(across(starts_with("post"), .names = "diff{sub('post', '', .col)}") - across(starts_with("pre")))

  preA preB postA postB diffA diffB
1    1    3     6     9     5     6
2    2    4     7     8     5     4
3    3    5     8     4     5    -1
like image 127
Ritchie Sacramento Avatar answered Sep 04 '25 19:09

Ritchie Sacramento