0
Phylum Abundance
Bacteroidetes 12
Firmicutes 4
Proteobacteria 3
Firmicutes 21
Firmicutes 9
Bacteroidetes 15
Proteobacteria 3
Bacteroidetes 8
Verrucomicrobia 2
Bacteroidetes 5

My question is I have a table like above in R studio. I want to write this table by combining the similar ones in the Phylum column in a new table and by adding the Abundance column while doing this, but I couldn't find a way. Sample output;

Phylum Abundance
Firmicutes 34
Bacteroidetes 40
Proteobacteria 6
Verrucomicrobia 2

Can you help me find the code that will allow me to output the above? Thank you from now.

AndrewGB
  • 16,126
  • 5
  • 18
  • 49

2 Answers2

1
df <- data.frame(Phylum = c("Bacteroidetes","Firmicutes","Proteobacteria","Firmicutes","Firmicutes","Bacteroidetes","Proteobacteria","Bacteroidetes","Verrucomicrobia","Bacteroidetes"),
                 Abundance = c(12,4,3,21,9,15,3,8,2,5))


df

           Phylum Abundance
1    Bacteroidetes        12
2       Firmicutes         4
3   Proteobacteria         3
4       Firmicutes        21
5       Firmicutes         9
6    Bacteroidetes        15
7   Proteobacteria         3
8    Bacteroidetes         8
9  Verrucomicrobia         2
10   Bacteroidetes         5

aggregate(Abundance~.,df,FUN=sum)

Output:

     Phylum Abundance
1   Bacteroidetes        40
2      Firmicutes        34
3  Proteobacteria         6
4 Verrucomicrobia         2
cgvoller
  • 873
  • 1
  • 14
1

You can use dplyr

library(dplyr)
df <- data.frame(Phylum = c("Bacteroidetes","Firmicutes","Proteobacteria","Firmicutes","Firmicutes","Bacteroidetes","Proteobacteria","Bacteroidetes","Verrucomicrobia","Bacteroidetes"),
                 Abundance = c(12,4,3,21,9,15,3,8,2,5))

df %>% 
  group_by(Phylum) %>% 
  summarize(Abundance = sum(Abundance)) %>% 
  ungroup()

Kev
  • 11
  • 1
  • I really thank you for solving my problem. I tried everything in the dplyr package but didn't know there was ungroup(). – Mücahit Kaya Jan 02 '22 at 21:52