Count unique count within groups and specific column in R

Viewed 28

Hel lo I have a df such as :

Col1 Col2 Col3
Group1 Seq_1:Sp1 Prot_1A
Group1 Seq_1:Sp1 Prot_1B
Group1 Seq_1:Sp1 Prot_1B
Group1 Seq_1:Sp3 Prot_1C
Group2 Seq_1:Sp5 Prot_1E
Group2 Seq_2:Sp5 Prot_1F
Group2 Seq_1:Sp6 Prot_1G
Group3 Seq_1:Sp7 Prot_1H_AB
Group3 Seq_1:Sp7 Prot_1Y

and I would like grouby each group in Col1: - count the mean number of different Col3 values

for Group1 there are 3 different Col3 values. for Group3 there are 2 different Col3 values.

  • count the mean number of different Col2 values

for Group1 there are 2 different Col2 values. for Group3 there are 1 different Col2 values. And store all the number for groups into :

 list_mean_nb_col2_values=c()
 list_mean_nb_col3_values=c()
1 Answers

We can use aggregate

aggregate(Col3 ~ Col1, df1, FUN = function(x) mean(table(x)))

Or with table

rowMeans(table(df1[c('Col1', 'Col3')]))
Related