我有Dataset,我想计算每个得分组(1-10)中KPI,CPM和CPC列的平均值以及计数时间列。
如何根据结果创建新表?
新表格如下:
score avg_KPI avg_CPC avg_CPM count_times
10
9
8
7
6
5
4
3
2
1
我尝试使用For方法,但它不起作用,
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])
}
答案 0 :(得分:1)
假设您的数据位于名为df的data.frame中,您是否只想要这个?
library(data.table)
setDT(df)[ ,.(lapply(.SD, mean), .N), by = score, .SDcols = c("KPI", "CPM", "CPC")]
或者你想要这个吗?
library(dplyr)
group_by(df, score) %>%
summarise(Mean_KPI = mean(KPI),
Mean_CPC = mean(CPC),
Mean_CPM = mean(CPM),
Sum_times = sum(times))