[英]Grouped linear regression prediction on different grouped by group in R
I'm trying to build models based on specific groups in a dataset and use the models generated to predict fit on a different dataset by following the group restrictions.我正在尝试基于数据集中的特定组构建模型,并使用生成的模型通过遵循组限制来预测不同数据集的拟合。 In other words, using the example below, models built using subset: cyl==4 of original data should be used only to predict subset: cyl==4 of new dataset (data1).换句话说,使用下面的示例,使用原始数据的子集:cyl==4 构建的模型应仅用于预测新数据集(data1)的子集:cyl==4。 Anyone can help with this interesting problem?任何人都可以帮助解决这个有趣的问题吗?
I tried to used data1%>% group_by(cyl)
to specify the new data but that didn't help我尝试使用data1%>% group_by(cyl)
来指定新数据,但这没有帮助
Thank you谢谢
library(broom)
library(dplyr)
library(purrr)
data1 <- head(mtcars,20)
x<-mtcars %>%
group_by(cyl) %>%
summarise(fit = list(lm(wt ~ mpg)),
data = list(cur_data())) %>%
mutate(col = map(fit, augment, newdata = data1%>% group_by(cyl)))```
Here is a quick way to do this这是一个快速的方法来做到这一点
library(dplyr)
models = mtcars %>% group_by(cyl) %>% do(model = lm(wt ~ mpg, data = .))
Then access the individual models with然后访问各个模型
library(broom)
tidy(models$model[[1]])
Another way to do the same -做同样的另一种方法 -
models <- mtcars %>%
nest_by(cyl) %>%
mutate(mod = list(lm(mpg ~ disp, data = data)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.