检查分类输入的结构
在本练习中,您将调用 model.matrix()(文档)来
查看 R 在建模时如何表示同时包含分类和数值输入的数据。
数据集 flowers(源自 Sleuth3 包)已为您加载。它包含以下列:
Flowers:meadowfoam 植物的平均花朵数量Intensity:对植物施加的光照处理强度Time:一个分类变量——光照处理在生命周期中的时间点(Late或Early)
最终目标是将 Flowers 建模为 Time 和 Intensity 的函数。
本练习是课程的一部分
R 中的监督学习:回归
练习说明
- 对
flowers调用str()函数,查看每一列的类型。 - 对列
flowers$Time使用unique()函数,查看Time可能取的值。共有多少个唯一值? - 创建一个公式,将
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
___