1

请注意,您从问题 4 构建的图形显示了log_wagesexp之间的二次或曲线关系。下一个任务是为每个种族级别“黑色”、“白色”和“其他”绘制三个二次函数。要估计二次拟合,可以使用以下函数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 函数,它似乎已经为您进行了计算。

4

1 回答 1

1

quad_fit考虑使用(如@StefanK 此处所示)的输出绘制拟合值,并用于by绘制所有不同的种族值:

reg_plot <- function(sub) {
   # PREDICTED DATA FOR LINE PLOT
   q_fit <- quad_fit(sub)
   predicted_df <- data.frame(wage_pred = predict(q_fit, sub), exp = sub$exp)

   # ORIGINAL SCATTER PLOT WITH PREDICTED LINE
   ggplot(data = sub) + 
     geom_point(aes(x = exp, y = log_wage, alpha = exp)) +
     labs(x = "Job Experience", y = "Log of Wage", 
          title = paste("Wage and Job Experience Plot for",    
                        sub$race[[1]], "in Salary Dataset") 
     geom_line(color='red', data = predicted_df, aes(x = exp, y = wage_pred))
}

# RUN GRAPHS FOR EACH RACE
by(salary_data, salary_data$race, reg_plot)
于 2019-03-09T18:27:53.703 回答