Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge rows in a data frame using R

Here is part of my data frame.

> df
  ACSK AEUJ AEXF AIWT ALGN AMFQ             Pathway
1    1    0    0    1    0    0    Genome_integrity
2    0    0    0    1    0    1                PI3K
3    0    0    0    0    0    0                  TF
4    0    0    0    0    1    0             RTK_RAS
5    0    0    0    0    1    0                PI3K
6    0    0    0    1    1    0 Epigenetic_modifier
7    0    0    1    0    0    0                PI3K

I want to merge the rows with the same value in the "Pathway" coulumn and calculate the sum of the merged cells. Below is the expected output.

> df2
  ACSK AEUJ AEXF AIWT ALGN AMFQ             Pathway
1    1    0    0    1    0    0    Genome_integrity
2    0    0    1    1    1    1                PI3K
3    0    0    0    0    0    0                  TF
4    0    0    0    0    1    0             RTK_RAS
5    0    0    0    1    1    0 Epigenetic_modifier

DATA

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

structure(list(ACSK = c(1, 0, 0, 0, 0, 0, 0), AEUJ = c(0, 0, 
0, 0, 0, 0, 0), AEXF = c(0, 0, 0, 0, 0, 0, 1), AIWT = c(1, 1, 
0, 0, 0, 1, 0), ALGN = c(0, 0, 0, 1, 1, 1, 0), AMFQ = c(0, 1, 
0, 0, 0, 0, 0), Pathway = c("Genome_integrity", "PI3K", "TF", 
"RTK_RAS", "PI3K", "Epigenetic_modifier", "PI3K")), row.names = c(NA, 
7L), class = "data.frame")

>Solution :

You can use across(everything()) from dplyr.

library(dplyr)
df1 %>%
  group_by(Pathway) %>%
  summarise(across(everything(), ~sum(.)))

  Pathway              ACSK  AEUJ  AEXF  AIWT  ALGN  AMFQ
  <chr>               <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Epigenetic_modifier     0     0     0     1     1     0
2 Genome_integrity        1     0     0     1     0     0
3 PI3K                    0     0     1     1     1     1
4 RTK_RAS                 0     0     0     0     1     0
5 TF                      0     0     0     0     0     0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading