简体   繁体   中英

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!

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

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))

We could also rep licate 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM