r的均值图表
我有一个具有学生考试成绩(学习者$ linacy_total)的数据集(学习者),他们的年级水平(即1年级1,2,3,...,12)及其性别(Learner $ Gender)。我想创建一个在X轴上具有等级的条形图,Y轴上的平均得分为每个等级(男性一列,一个是女性),这样我就可以看到男孩/女孩是如何做的在每个等级。我可以使用以下代码轻松地创建每个等级的总体平均图:
fig.dist <- split(learner$literacy_total, learner$learner_grade)
fig.mean <- sapply(fig.dist, mean, na.rm = TRUE)
barplot(fig.mean)
但是如何对这些代码进行分组,以便每个年级可以单独看到男孩/女孩的平均考试成绩。
在其他问题中,我看到的代码要么将类别分组或绘制手段,但是我正在努力将两者放在一起。
I have a data set (learner) with student test scores (learner$literacy_total), their grade level (ie. grade 1, 2, 3, ..., 12), and their gender (learner$gender). I'd like to create a bar plot that has grade on the x axis, and the average score on the y axis, with two columns for each grade (one for males and one for females) so I can see how boys/girls do in each grade. I can easily create a plot of the overall average for each grade using the following code:
fig.dist <- split(learner$literacy_total, learner$learner_grade)
fig.mean <- sapply(fig.dist, mean, na.rm = TRUE)
barplot(fig.mean)
But how do I group these so that for each grade I can see the average test scores for boys/girls separately.
In other questions I've seen code that either groups categories or graphs the means, but I'm struggling with how to put the two together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要扩展 @detroyejr的答案,请考虑
tapply
将向量切成各种因子,并将诸如sean
之类的函数应用于每个子集返回返回命名向量或矩阵的每个子集。但是,要与您的原始总体平均值小号保持一致,请将
tapply
与t()
用于男性/女性/女性 Rownames 和1-12等级如 colnames 。然后使用base = true
用于未堆放的条。用随机数据演示:
To extend @detroyejr's answer, consider
tapply
which slices a vector by various factor(s) and applies a function such asmean
to each subset returning a named vector or matrix.However, to align to your original overall mean barplot, transpose the
tapply
result witht()
for male/female rownames and 1-12 grades as colnames. Then usebeside=TRUE
for unstacked bars.To demonstrate with random data:
您可以使用
tapply
(请参阅在这里或帮助(tapply)
以获取更多信息)。因此,使用您的数据集这样的东西:在此示例中,
tapply
本质上破坏linacy_total
中的每种组合learner_grade
和gender
可用并计算每个分组的平均值。您可以使用另一个示例看到:如果提供可重复的示例,则更容易回答,但这可能会使您开始。
You can use
tapply
(see here orhelp(tapply)
for more info). So, something like this using your dataset:In this example,
tapply
essentially breaksliteracy_total
into each combination oflearner_grade
andgender
available and computes the mean value at each grouping. You can see another example using:It's easier to answer if you provide a reproducible example, but this might get you started.
使用
ggplot
和dplyr
a solution using
ggplot
anddplyr