请注意,您从问题 4 构建的图形显示了log_wages与exp之间的二次或曲线关系。下一个任务是为每个种族级别“黑色”、“白色”和“其他”绘制三个二次函数。要估计二次拟合,可以使用以下函数quad_fit:
```{r}
quad_fit <- function(data_sub) {
return(lm(log_wage~exp+I(exp^2),data=data_sub)$coefficients)
}
quad_fit(salary_data)
```
上述函数计算最小二乘二次拟合并返回系数 a1、a2、a3,其中
Y(帽子) = a1 + a2x + a3x^2
其中 Y(hat) = log(wage) 和 x = exp
使用ggplot完成此任务或使用基本 R 图形获得部分功劳。确保包括图例和适当的标签。
我的尝试
blackfit <- quad_fit(salary_data[salary_data$race == "black",])
whitefit <- quad_fit(salary_data[salary_data$race == "white",])
otherfit <- quad_fit(salary_data[salary_data$race == "other",])
yblack <- blackfit[1] + blackfit[2]*salary_data$exp + blackfit[3]*(salary_data$exp)^2
ywhite <- whitefit[1] + whitefit[2]*salary_data$exp + whitefit[3]*(salary_data$exp)^2
yother <- otherfit[1] + otherfit[2]*salary_data$exp + otherfit[3]*(salary_data$exp)^2
soloblack <- salary_data[salary_data$race == "black",]
solowhite <- salary_data[salary_data$race == "white",]
soloother <- salary_data[salary_data$race == "other",]
ggplot(data = soloblack) +
geom_point(aes(x = exp, y = log_wage)) +
stat_smooth(aes(y = log_wage, x = exp), formula = y ~ yblack)
这只是使用 for race == "black" 过滤的数据的第一次尝试。我不清楚公式应该是什么样子,因为通过 quad_fit 函数,它似乎已经为您进行了计算。