perherring
perherring

Reputation: 23

Subtracting multiple rows from the same row in R

I am looking to subtract multiple rows from the same row within a dataframe.

For example:

Group   A    B    C
   A    3    1    2
   B    4    0    3
   C    4    1    1
   D    2    1    2

This is what I want it to look like:

Group   A    B    C
   B    1    -1   1
   C    1    0    -1
   D    -1   0    0

So in other words:

Row B - Row A

Row C - Row A

Row D - Row A

Thank you!

Upvotes: 0

Views: 221

Answers (3)

akrun
akrun

Reputation: 887951

We could also replicate the first row and substract from the rest

cbind(data[-1, 1, drop = FALSE],  data[-1, -1] - data[1, -1][col(data[-1, -1])])

-output

#  Group  A  B  C
#2     B  1 -1  1
#3     C  1  0 -1
#4     D -1  0  0

Upvotes: 1

Ian Campbell
Ian Campbell

Reputation: 24888

Here's an approach with base R:

data[-1] <- do.call(rbind,
                    apply(data[-1],1,function(x) x - data[1,-1])
                    )
data[-1,]
#  Group  A  B  C
#2     B  1 -1  1
#3     C  1  0 -1
#4     D -1  0  0

Data:

data <- structure(list(Group = c("A", "B", "C", "D"), A = c(3L, 4L, 4L, 
2L), B = c(1L, 0L, 1L, 1L), C = c(2L, 3L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 3

Matt
Matt

Reputation: 7413

Here's a dplyr solution:

library(dplyr)

df %>% 
      mutate(across(A:C, ~ . - .[1])) %>% 
      filter(Group != "A")

This gives us:

   Group  A  B  C
1:     B  1 -1  1
2:     C  1  0 -1
3:     D -1  0  0

Upvotes: 3

Related Questions