如何按组获取变量的平均值,并在 data_table 中生成一个采用该值的新变量

How to get the mean of a variable by group, and produce a new variable in the data_table taking that value

我找到了很多关于 R 中 dplyr group_by() 函数的其他问题的解决方案,就像下面的那个建议 summarize_each() 函数简单地打印 mean 数据集中每个有条件定义的行组的所有变量观察值。

不幸的是,我需要能够创建一个新变量附加到每一行,这是测量值的平均值(在本例中为女性身高),以便我以后可以将它用作预测变量回归。

这个例子是否有任何不同的解决方案允许某人运行一个regression/classification基于组的平均值(在这个例子中是身高)的过程?

DF <- data.frame(Height = rnorm(100, 170, 5),
                 Weight = rnorm(100, 55, 5),
                 Gender = c(rep("male", 50), rep("female", 50)))


BMI <-  function(height,weight){(weight/(height)^2*10000)}

library(dplyr)
DF %>% 
  group_by(Gender) %>% 
  mutate(bmi = BMI(Height, Weight)) %>% 
  summarise(mean_bmi = mean(bmi))

您不需要 summarise 行代码。您可以将 mean 直接添加到您的 mutate.

DF <- DF %>% 
  group_by(Gender) %>% 
  mutate(bmi = mean(BMI(Height, Weight))) %>% 
  ungroup()

然后你可以运行你的回归模型与这个数据集。