檢視類別型輸入的結構
在這個練習中,你會呼叫 model.matrix()(文件)來
觀察 R 在建模時如何同時表示類別型與數值型的輸入。
資料集 flowers(源自 Sleuth3 套件)已為你載入。它包含下列欄位:
Flowers:meadowfoam 植物的平均花朵數Intensity:施加在植物上的光照處理強度Time:類別變數——光照處理在生命週期中的時間點(Late或Early)
最終目標是將 Flowers 作為 Time 與 Intensity 的函數來進行預測。
本練習屬於課程
R 中的監督式學習:回歸
練習說明
- 對
flowers呼叫str()函式,查看各欄位的型別。 - 對欄位
flowers$Time使用unique(),查看Time可能的取值。有多少個不重複的值? - 建立一個 formula,將
Flowers表示為Intensity與Time的函數。指定給變數fmla,並列印它。 - 使用
fmla與model.matrix(),為資料框flowers建立模型矩陣。指定給變數mmat。 - 使用
head()檢視flowers的前 20 列。 - 接著檢視
mmat的前 20 列。- 數值欄位
Intensity有不同嗎? - 來自
flowers的類別欄位Time發生了什麼變化? Time == 'Early'如何被表示?那Time == 'Late'呢?
- 數值欄位
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Call str on flowers to see the types of each column
___
# Use unique() to see how many possible values Time takes
___
# Build and print a formula to express Flowers as a function of Intensity and Time: fmla
(fmla <- ___("Flowers ~ Intensity + Time"))
# Use fmla and model.matrix to see how the data is represented for modeling
mmat <- ___
# Examine the first 20 lines of flowers
___
# Examine the first 20 lines of mmat
___