在嵌套数据框上建模
您将使用美国陆军 ANSUR II(ANSUR II)人体测量数据集,已预加载为 ansur_df。目标是按性别对数据进行嵌套,从而可以同时训练两个线性模型,每个性别一个。这些模型将根据身高(stature)和腰围(waist circumference)来推断一个人的体重。然后,您将对数据进行展开,以检查 broom 包中 glance() 函数生成的模型统计量。
已为您预加载 dplyr、broom 和 purrr 包。
旁注: 在提供的代码中,purrr 包的 map() 函数用于对每个嵌套的数据框应用函数。如果您喜欢在管道中使用函数,值得了解一下这个包!
本练习是课程的一部分
使用 tidyr 重塑数据
练习说明
- 按
sex分组数据。 - 对数据进行嵌套。
- 对
glanced列进行展开。
交互式实操练习
通过完成这段示例代码来试试这个练习。
ansur_df %>%
# Group the data by sex
___ %>%
# Nest the data
___ %>%
mutate(
fit = map(data, function(df) lm(weight_kg ~ waist_circum_m + stature_m, data = df)),
glanced = map(fit, glance)
) %>%
# Unnest the glanced column
___