1

I'm trying to group by a column in my data frame and show the count of occurrences and the mean.

an example is the tables below, I want to group by id, and display the count of occurrences of that id and the mean of x.

id   x   
a   4     
a   8   
b   6      
b   10   
b   6    
c   4   
c   12    

my output should be like this

id  mean count  
a   6     2
b   11    3 
c   8     2
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Anas Baheh
  • 137
  • 2
  • 13

2 Answers2

2

you could use the following code

## your data
df <-read.table(header = TRUE, text = "
    id   x   
    a   4     
    a   8   
    b   6      
    b   10   
    b   6    
    c   4   
    c   12  ")

library(dplyr)
df %>% group_by(id) %>% 
       summarize(mean = mean(x), count = n())

yielding:

# A tibble: 3 x 3
  id     mean count
  <fct> <dbl> <int>
1 a      6        2
2 b      7.33     3
3 c      8        2
KoenV
  • 4,113
  • 2
  • 23
  • 38
1

You can use aggregate with mean and length:

aggregate(x ~ id, a, function(x) c("mean" = mean(x), "count" = length(x)))
#  id   x.mean  x.count
#1  a 6.000000 2.000000
#2  b 7.333333 3.000000
#3  c 8.000000 2.000000

Data:

a <- structure(list(id = c("a", "a", "b", "b", "b", "c", "c"), x = c(4L, 
8L, 6L, 10L, 6L, 4L, 12L)), class = "data.frame", row.names = c(NA, 
-7L))
GKi
  • 37,245
  • 2
  • 26
  • 48