1

我将如何在以下线性模型中提取特定棒球队的提取残差数据?例如,我将如何提取“CLE”的残差?

library(Lahman)
library(dplyr)
library(broom)

# create baseball team data
data(Teams)
teams <- Teams
teams <- teams %>% mutate(win_percentage = (W / (W + L)) * 100)

# summarize baseball team salary by year
salaries <- Salaries
salaries <- salaries %>% 
  group_by(teamID, yearID, lgID) %>%
  summarise(payroll_M = sum(as.numeric(salary)) / 10^6) %>% 
  ungroup()

# add winning percentage to the salary table
salaries <- teams %>% 
  select(yearID, teamID, win_percentage) %>% 
  right_join(salaries, by = c("yearID", "teamID"))

# compute linear model of winning vs team salary
model <- salaries %>% 
  group_by(yearID) %>%
  do(fit = augment(lm(win_percentage ~ payroll_M, data = .)))

# extract residuals for Cleveland ??????
4

1 回答 1

3

你很接近,但需要对augment线路进行两次更改。

  1. 您将生成的(增强的)数据框保存到名为fit. 相反,请尝试直接将其提供给do(删除fit =)。

  2. 增强功能需要将teamID列保留为结果数据的一部分,即使它不在模型中。请注意,正是为此目的augment需要第二个参数(请参阅更多信息)。datahelp(augment.lm)

因此,新行将如下所示:

do(augment(lm(win_percentage ~ payroll_M, data = .), data = .))

生成的数据框每个原始观测值将有一行,并将包括teamID残差和拟合值(允许您过滤CLE)。

于 2016-03-23T04:42:47.287 回答