聚合套装以比较它们的差异
要比较两个具体套装及其由哪些 LEGO 零件组成,您需要先把数据按不同主题进行聚合。此外,正如视频中所示,我们还要添加一列,用于表示每个套装中某类零件所占的比例,而不仅仅看零件数量本身。
inventory_parts_themes 表已为您预加载。
inventory_parts_themes <- inventories %>%
inner_join(inventory_parts, by = c("id" = "inventory_id")) %>%
arrange(desc(quantity)) %>%
select(-id, -version) %>%
inner_join(sets, by = "set_num") %>%
inner_join(themes, by = c("theme_id" = "id"), suffix = c("_set", "_theme"))
本练习是课程的一部分
使用 dplyr 进行数据表连接
练习说明
- 为
"Batman"主题添加筛选,创建batman_colors对象。 - 在
batman_colors中添加一列fraction,其值为 total 除以 total 的总和。 - 重复上述步骤,对
"Star Wars"套装数据进行筛选和聚合,创建star_wars_colors对象。 - 在
star_wars_colors中添加fraction列,显示 total 的占比。
交互式实操练习
通过完成这段示例代码来试试这个练习。
batman_colors <- inventory_parts_themes %>%
# Filter the inventory_parts_themes table for the Batman theme
filter(name_theme == ___) %>%
group_by(color_id) %>%
summarize(total = sum(quantity)) %>%
# Add a fraction column of the total divided by the sum of the total
mutate(___)
# Filter and aggregate the Star Wars set data; add a fraction column
star_wars_colors <- inventory_parts_themes %>%
___