Jeffery Chen
Jeffery Chen

Reputation: 323

How to average and count in each group and creating a new table

I have a Dataset, I want to calculate average of KPI, CPM and CPC column and count times column in each score group(1-10).

How to create a new table according results?

A new table looks like:

score   avg_KPI avg_CPC avg_CPM count_times
10  
9   
8   
7   
6   
5   
4   
3   
2   
1   

I try to use For method,but it doesn't work,

for (i in 1:10) {
  aa <- subset(dataset1,score== i )
  macroAvgs<-colMeans(aa[,2:4])
  df <- rbind(score="i",KPI=macroAvgs[1],CPC=macroAvgs[2],CPM=macroAvgs[3],times=count(aa[5])
}

Upvotes: 1

Views: 1970

Answers (1)

grrgrrbla
grrgrrbla

Reputation: 2589

assuming your data is in a data.frame called df, do you just want this?

library(data.table)
setDT(df)[ ,.(lapply(.SD, mean), .N), by = score, .SDcols = c("KPI", "CPM", "CPC")]

or do you want this?

library(dplyr)
group_by(df, score) %>%
    summarise(Mean_KPI = mean(KPI),
              Mean_CPC = mean(CPC),
              Mean_CPM = mean(CPM),
              Sum_times = sum(times))

Upvotes: 1

Related Questions