How to calculate the mean of specific rows in R?

十年热恋 提交于 2019-12-02 07:18:49
Jilber Urbina

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.

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

which produce:

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.

Using the sqldf package (assuming df is your table)

library(sqldf)
sqldf("SELECT names, avg(Y1) as mean_Y1, avg(Y2) as mean_Y2 FROM df GROUP BY names")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!