计算组均值和总体均值

时间:2018-08-10 20:27:43

标签: r dplyr tidyverse

我有一个数据框架,其中包含多个变量,我希望获取这些变量的值,以及一个要分组的变量。然后,我想获得每个组的均值在总体均值中所占的比例。

我整理了以下内容,但很笨拙。

您将如何使用dplyrdata.table进行操作?可以同时返回中间步骤(组和总体均值)和最终比例的选项的加分。

library(tidyverse)

set.seed(1)
Data <- data.frame(
  X1 = sample(1:10),
  X2 = sample(11:20),
  X3 = sample(21:30),
  Y = sample(c("yes", "no"), 10, replace = TRUE)
)

groupMeans <- Data %>% 
  group_by(Y) %>%
  summarize_all(funs(mean))

overallMeans <- Data %>% 
  select(-Y) %>% 
  summarize_all(funs(mean))

index <- sweep(as.matrix(groupMeans[, -1]), MARGIN = 2,  as.matrix(overallMeans), FUN = "/")

3 个答案:

答案 0 :(得分:2)

这是另一种dplyr解决方案

index <- as.data.frame(Data %>% 
    group_by(Y) %>%
    summarise_all(mean) %>%
    select(-Y)  %>%
    rbind(Data %>% select(-Y) %>% summarise_all(mean))%>%
    mutate_all(funs( . / .[3])))[1:2,]

答案 1 :(得分:0)

这里是一种可能的dplyr解决方案,其中包含您想要的一切:

Data %>% 
  group_by(Y) %>%
  summarise(
    group_avg_X1 = mean(X1),
    group_avg_X2 = mean(X2),
    group_avg_X3 = mean(X3)
  ) %>%
  mutate(
    overall_avg_X1 = mean(group_avg_X1),
    overall_avg_X2 = mean(group_avg_X2),
    overall_avg_X3 = mean(group_avg_X3),
    proportion_X1 = group_avg_X1 / overall_avg_X1,
    proportion_X2 = group_avg_X2 / overall_avg_X2,
    proportion_X3 = group_avg_X3 / overall_avg_X3
  )

# # A tibble: 2 x 10
#   Y     group_avg_X1 group_avg_X2 group_avg_X3 overall_avg_X1 overall_avg_X2 overall_avg_X3 proportion_X1
#   <fct>        <dbl>        <dbl>        <dbl>          <dbl>          <dbl>          <dbl>         <dbl>
# 1 no             6.6         14.6         25.8            5.5           15.5           25.5           1.2
# 2 yes            4.4         16.4         25.2            5.5           15.5           25.5           0.8
# # ... with 2 more variables: proportion_X2 <dbl>, proportion_X3 <dbl>

答案 2 :(得分:0)

这是使用data.table的方法:

#data
library(data.table)
set.seed(1)
dt <- data.table(
  x1 = sample(1:10),
  x2 = sample(11:20),
  x3 = sample(21:30),
  y = sample(c("yes", "no"), 10, replace = TRUE)
)

# group means
group_means <- dt[ , lapply(.SD, mean), by=y, .SDcols=1:3]

# overall means
overall_means <- dt[ , lapply(.SD, mean), .SDcols=1:3]

# clunky combination (sorry!)
group_means[ , perc_x1 := x1 / overall_means[[1]] ]
group_means[ , perc_x2 := x2 / overall_means[[2]] ]
group_means[ , perc_x3 := x3 / overall_means[[3]] ]