ePoQ
ePoQ

Reputation: 463

Difference between multiple columns within a single dataframe

I am looking at a simple way to do the difference between multiple columns within a single dataframe and get the results within the same dataframe. Here is a reproducible example where I would like to subtract var1 from var1.bis, var2 for var2.bis, etc.

df1 <- data.frame(var1 = sample(1:10),
                  var2 = sample(1:10),
                  var3 = sample(1:10),
                  var1.bis = sample(1:10),
                  var2.bis = sample(1:10),
                  var3.bis = sample(1:10))

Upvotes: 2

Views: 110

Answers (1)

Parfait
Parfait

Reputation: 107567

Consider subtracting blocks of variables like two matrices using grep for pattern matching on colnames. You can even assign result as new columns:

bis_cols <- grep("\\.bis", colnames(df1), invert=FALSE)
non_bis_cols <- grep("\\.bis", colnames(df1), invert=TRUE)

df1[paste0("var_diff_", non_bis_cols)] <- df1[,bis_cols] - df1[,non_bis_cols]

Online Demo

Upvotes: 1

Related Questions