你其實已經在操作物件了
在 Introduction to R 課程中,你已經看過數個常見的 R 物件,例如 numeric、logical、character 向量,以及 data.frame。OOP 的一個原則是:同一個函式可以對不同種類的物件表現出不同的行為。
summary()(文件)就是很好的例子。因為不同型別的變數需要以不同方式摘要,所以根據你傳入的物件,顯示給你的輸出也會不同。
本練習屬於課程
在 R 中使用 S3 與 R6 的物件導向程式設計
練習說明
- 執行編輯器中提供的程式碼,建立數個不同型別的物件。
- 針對每個物件(一次一個)呼叫
summary(),然後查看輸出並試著理解它。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create these variables
a_numeric_vector <- rlnorm(50)
a_factor <- factor(
sample(c(LETTERS[1:5], NA), 50, replace = TRUE)
)
a_data_frame <- data.frame(
n = a_numeric_vector,
f = a_factor
)
a_linear_model <- lm(dist ~ speed, cars)
# Call summary() on the numeric vector
summary(a_numeric_vector)
# Do the same for the other three objects
___
___
___