嘗試性的模型
你拿到一個資料集,記錄了兩個物體在不同距離下的重力作用力測量值。你的挑戰是建立一個簡單的模型,根據給定的距離來預測此作用力。起初,你想先用最基本的線性迴歸。資料包含 120 組 distance 與 force 的配對,並已載入為 newton。
本練習屬於課程
R 的特徵工程
練習說明
- 使用 base
R的線性模型函式,為newton資料建立線性模型,並指定給lr_force。 - 將預測值與原始
newton資料繫結,建立新的資料框df。 - 使用
ggplot()繪製force對distance的散佈圖。 - 在散佈圖上加入以擬合值繪製的迴歸線。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Build a linear model for the newton the data and assign it to lr_force
lr_force <- ___(force ~ distance, data = ___)
# Create a new data frame by binding the prediction values to the original data
df <- newton %>% ___(lr_pred = predict(lr_force))
# Generate a scatterplot of force vs. distance
df %>%
ggplot(aes(x = distance, y = force)) +
geom____() +
# Add a regression line with the fitted values
geom_line(aes(y = ___), color = "blue", lwd = .75) +
ggtitle("Linear regression of force vs. distance") +
theme_classic()