箱线图
比较多个分布的一个简单方法是箱线图。下面的代码将帮助您构建多个箱线图,形成紧凑的可视化。
本练习中对象 all_book_polarity 已加载。该数据框包含两列:book 和 polarity。它汇总了对所有书籍应用 qdap 的 polarity() 函数的结果。下面是该大型对象的前 3 行。
| book | polarity | |
|---|---|---|
| 14 | huck | 0.2773501 |
| 22 | huck | 0.2581989 |
| 26 | huck | -0.5773503 |
本练习将介绍 tapply(),它可以在不规则数组上应用函数。您输入一个数值向量,再输入一个因子向量。对于每个因子与数值的组合,会应用第三个参数指定的函数,例如 min()。例如,下面是在两个向量上使用 tapply() 的代码。
f1 <- as.factor(c("Group1", "Group2", "Group1", "Group2"))
stat1 <- c(1, 2, 1, 2)
tapply(stat1, f1, sum)
结果是一个数组,其中 Group1 的值为 2(1+1),Group2 的值为 4(2+2)。
本练习是课程的一部分
R 中的情感分析
练习说明
- 由于已加载,请使用
str()查看all_book_polarity。 - 使用
tapply(),传入all_book_polarity$polarity、all_book_polarity$book和summary()函数。这将按书名输出其polarity()分数的汇总统计,共 4 本书。通常会看到 Oz 和 Huck Finn 的平均值高于 Agamemnon 或 Moby Dick。请特别留意中位数。 - 使用
ggplot()传入all_book_polarity创建箱线图。- 美学映射应为
aes(x = book, y = polarity)。 - 使用
+添加geom_boxplot(),并设置col = "darkred"。请特别关注每个箱体中表示中位数的深色线。 - 接着再添加一层
geom_jitter()`,为每个词添加散点。
- 美学映射应为
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Examine
___
# Summary by document
___
# Box plot
ggplot(___, aes(x = ___, y = ___)) +
___(fill = c("#bada55", "#F00B42", "#F001ED", "#BA6E15"), col = "___") +
___(position = position_jitter(width = 0.1, height = 0), alpha = 0.02) +
theme_gdocs() +
ggtitle("Book Polarity")