如何计算R中特定行的均值? [英] How to calculate the mean of specific rows in R?

查看:1219
本文介绍了如何计算R中特定行的均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据文件,如下例所示,但是更大

I have a data file as following example but much more larger

names    num    Y1  Y2
William  1  4.71    7.4
William  2  3.75    8
William  3  4.71    7.9
Katja    1  5.83    8.5
Katja    2  5.17    7.1
Katja    3  6.08    7.4
Aroma    1  4.04    7.5
Aroma    2  5       6.9
Aroma    3  4.3     7.9
...

我必须为Y1和Y2计算每三个相同名称(第一列)的平均值.然后分别用每个名称的平均值Y1和Y2制作条形图.因此,在x轴上,我将具有名称,在y轴上,将具有均值.有人可以帮我吗?

I have to calculate the mean for each 3 of the same names (first column) for Y1 and Y2. And then make a bar chart by the average of each name with Y1 and Y2, separately. So on the x axis I will have the names and on the y axis the mean. Could anybody help me with this?

推荐答案

您也可以使用aggregate.有关更多详细信息,请参见?aggregate.

You can also use aggregate. See ?aggregate for further details.

> aggregate(.~names, FUN=mean, data=df[, -2])
    names       Y1       Y2
1   Aroma 4.446667 7.433333
2   Katja 5.693333 7.666667
3 William 4.390000 7.766667

看看这篇文章为每个组取平均值的另一种选择.

Take a look at this post for another alternatives of taking mean for each group.

对于条形图,请使用R base barplot函数,尽管还有其他替代方法,例如ggplot2图形.

For the bar plots use R base barplot function although there other alternatives such as ggplot2 graphics.

barplot(DF[,2], names.arg=DF$names, ylab="mean of Y1", las=1) # for Y1
barplot(DF[,3], names.arg=DF$names, ylab="mean of Y2", las=1) # for Y2

会产生:

由于您是R的新手,因此建议阅读 An R 简介,这是您学习R基础知识的一个很好的起点.

As you are very new to R, I recommend to read An introduction to R which is a good starting point you to learn the basics of R.

这篇关于如何计算R中特定行的均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆