将for循环转换为dplyr语句-与平均值的偏差

将for循环转换为dplyr语句-与平均值的偏差,r,for-loop,dplyr,R,For Loop,Dplyr,我的目标是获得每组测量值与该测量值平均值的偏差 我的数据如下所示: Cluster Media_Name count 1 1 20minutes 9 2 1 AFP 7 3 1 BFM 5 4 1 BFMTV 6 5 2 AFP 12 6 2 BFM 4 7 2 BFMTV 5 在公式中: data <- data.frame(Cluste

我的目标是获得每组测量值与该测量值平均值的偏差

我的数据如下所示:

Cluster Media_Name  count
1   1   20minutes   9
2   1   AFP         7
3   1   BFM         5
4   1   BFMTV       6
5   2   AFP         12
6   2   BFM         4
7   2   BFMTV       5
在公式中:

data <- data.frame(Cluster = c("1","1","1","1","2","2","2"), Media_Name = c("20Minutes", "AFP", "BFM", "BFMTV", "AFP", "BFM", "BFMTV"), count = c(9,7,5,6,12,4,5))
2-我使用for循环获得每个媒体名称(第二个分类变量)与聚类平均值的偏差:

for (i in 1:nrow(data)) {

  cluster <- data$Cluster[i]

  moyenneducluster <- clusterMean$clusterMean[clusterMean$Cluster==cluster]

  data$deviationFromClusterMean[i] <- data$count[i]/moyenneducluster

}

有什么想法吗?

您不需要单独定义
clusterMean
。以下方面应起作用:

data %>% 
  group_by(Cluster) %>% 
  mutate(deviationFromClusterMean = count/mean(count))

您不需要单独定义
clusterMean
。以下方面应起作用:

data %>% 
  group_by(Cluster) %>% 
  mutate(deviationFromClusterMean = count/mean(count))

您还可以使用
ave
from
base R

  with(data, count/ave(count, Cluster, FUN=mean))
  #[1] 1.3333333 1.0370370 0.7407407 0.8888889 1.7142857 0.5714286 0.7142857

您还可以使用
ave
from
base R

  with(data, count/ave(count, Cluster, FUN=mean))
  #[1] 1.3333333 1.0370370 0.7407407 0.8888889 1.7142857 0.5714286 0.7142857