我想要应用GroupWise多项式模型,并求解它,以获得每个组的y最高时的x值.我可以一次为一组人做这件事,比如

library(tidyverse)

#Create soem data
df = data.frame(Group = c("A", "A","A","A","A","A","A","A","A","A","A","A",
                            "B", "B","B","B","B","B","B","B","B","B","B","B"),
       price = c(448, 560, 575, 500, 612, 600, 610, 590, 589, 532, 577, 560,
                 454, 568, 584, 506, 617, 608, 617, 599, 598, 537, 583, 567),
       score = c(83, 86, 89, 85, 89, 90, 91, 91, 91, 85, 88, 93,
                 89, 94, 98, 91, 94, 98, 98, 100, 100, 90, 94, 100))

#Subset group A
data <- df %>% 
  subset(Group %in% "A")

#Plot it
with(data, plot(x = score, y = price,
                pch=19, xlab = "Score", ylab = "Price"))

#Develop the polynomial model
model <- lm(price ~ score + I(score^2), data = data)

xx <- seq(min(data$score, na.rm = T), max(data$score, na.rm = T), 0.01)

lines(xx,  model$coefficients[[3]]*xx^2 + model$coefficients[[2]]*xx + 
        model$coefficients[[1]], col='blue', lwd = 3)

#Optimum score calculation
xoptimum <- -model$coefficients[[2]]/2/model$coefficients[[3]]
abline(v=xoptimum, col="red")

enter image description here

现在,我如何使用tidyverse框架来拟合和求解这两组的多项式模型?我的原始数据集中有很多组.

推荐答案

您可以使用nestmap来处理数据组:

library(tidyverse)

df %>%
  nest(data = -Group) %>%
  mutate(model = map(data, ~ lm(price ~ score + I(score^2), data = .x))) %>%
  mutate(x_opt = unlist(map(model, ~-.x$coef[[2]]/2/.x$coef[[3]]))) %>%
  mutate(y_opt = unlist(map2(x_opt, model, ~predict(.y, list(score = .x))))) %>%
  select(Group, x_opt, y_opt)
#> # A tibble: 2 x 3
#> Group x_opt y_opt
#> <chr> <dbl> <dbl>
#> 1 A   89.9  597.
#> 2 B   97.0  607.

要使用gglot绘制它,我们可以这样做

df %>%
  nest(data = -Group) %>%
  mutate(model = map(data, ~ lm(price ~ score + I(score^2), data = .x))) %>%
  mutate(x_opt = unlist(map(model, ~-.x$coef[[2]]/2/.x$coef[[3]]))) %>%
  mutate(y_opt = unlist(map2(x_opt, model, ~predict(.y, list(score = .x))))) %>%
  unnest(data) %>%
  ggplot(aes(score, price)) +
  geom_point() +
  geom_smooth(method = lm, formula = y ~ x + I(x^2), se = FALSE) +
  geom_vline(aes(xintercept = x_opt), color = "red") +
  geom_hline(aes(yintercept = y_opt), linetype = 2) +
  theme_bw() +
  facet_grid(.~Group)

enter image description here

R相关问答推荐

如何创建具有总计列和ggplot 2所有条线的百分比标签的堆叠条形图?

如何判断某列中由某些行组成的百分比

R中的枢轴/转置

对lme 4对象运行summary()时出错(diag中的错误(from,names = RST):对象unpackedMatrix_diag_get找不到)

带有叠加饼图系列的Highmap

在R中创建一个包含转换和转换之间的时间的列

Highcharter多次钻取不起作用,使用不同方法

如何在编辑列时更新可编辑数据表,并使用该表在Shiny中执行连续计算

是否可以创建一个ggplot与整洁判断的交互作用

计算时间段的ECDF(R)

如何得到每四个元素向量R?

根据1个变量绘制 colored颜色 发散的 map ,由另一个变量绘制饱和度,ggplot2不工作

按多列统计频次

从多层嵌套列表构建Tibble?

有没有办法一次粘贴所有列

变长向量的矢量化和

R -基线图-图形周围的阴影区域

如何阻止围堵地理密度图?

主题(Legend.key=Element_RECT(Fill=&Quot;White&Quot;))不起作用

计算多变量的加权和