【问题标题】:Fit data with proportional dependent variable用比例因变量拟合数据
【发布时间】:2017-07-26 04:24:12
【问题描述】:

这是我的问题的简化版本,带有示例数据:

每年,我都会在我的院子里找到 40 个球。其中一定比例是红色的。我想模拟一段时间内红球的比例。

library(tidyverse)
library(modelr)

# generate some proportion data that changes by year
data = tibble(
  year = 2011:2020, 
  reds = 1:10, # red balls
  total = 40, # total number of balls
  propRed = reds / total # proportion of red balls each year
)

# fit to a model
model = glm(propRed ~ year, XXX_WHAT_GOES_HERE_XXX, data)

# graph the model's prediction and the data
tibble(year = 2000:2030) %>% 
  modelr::add_predictions(model, "propRed") %>% 
  ggplot() + 
    aes(y=propRed, x=year) + 
    geom_line() +
    geom_point(data=data)

【问题讨论】:

  • 这可以是逻辑回归。使用 glm(cbind(reds, total - reds) ~ year, family = 'binomial', data = data) 之类的方式调用 glm
  • 不清楚你在问什么。此外,您可能希望在 Cross Validated 中发帖。
  • @bouncyball:我跑了tibble(year = 2000:2030) %>% predict.glm(model, .),它预测出负值,这是不可能的。
  • @sharoz 这些预测是对数赔率 (read the documentation),将 add_predictions 行替换为 mutate(propRed = predict(model, newdata = ., type = 'response'))
  • 谢谢! type = 'response' 是我需要的!如果您将其添加为答案,我会检查一下。

标签: r statistics


【解决方案1】:

这是我们可以使用逻辑回归的情况,使用glm的公式界面中的cbind(successes, failures)选项:

model <- glm(cbind(reds, total - reds) ~ year, family = 'binomial', data = data)

tibble(year = 2000:2030) %>% 
    mutate(propRed = predict(model, newdata = ., type = 'response')) %>%
    ggplot() + 
    aes(y=propRed, x=year) + 
    geom_line() +
    geom_point(data=data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    相关资源
    最近更新 更多