Sven C. Koehler
2003-Dec-17 07:27 UTC
[R] Easiest way to get the mean of a row of a data.frame?
Dear r-helpers! I am kind of new to R. I would like to calculate the mean of the numbers of this expression: data(USArrests) USArrests[row.names(M) == "Alabama",] class() tells me it's a ``data.frame,'' what I actually desire is to get all numbers of a row as a vector or a list to let mean() calculate the mean of the whole row. (I know this doesn't make sense with USArrests, I just used it here instead of my very own data.frame.) Thank you very much! Bye Sven
Prof Brian Ripley
2003-Dec-17 07:42 UTC
[R] Easiest way to get the mean of a row of a data.frame?
rowMeans(mydf) will do this for a data frame mydf. Be careful though to use it only with all-numeric data frames (there is an implicit as.matrix going on), and often it makes more sense to store such data in a matrix. apply(mydf, 1, mean) would also work, but is slower. On Wed, 17 Dec 2003, Sven C. Koehler wrote:> I am kind of new to R. > I would like to calculate the mean of the numbers of this expression: > > data(USArrests) > USArrests[row.names(M) == "Alabama",] > > class() tells me it's a ``data.frame,'' what I actually desire is to get > all numbers of a row as a vector or a list to let mean() calculate the mean > of the whole row. (I know this doesn't make sense with USArrests, I just > used it here instead of my very own data.frame.)-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595
Philipp Pagel
2003-Dec-17 08:43 UTC
[R] Easiest way to get the mean of a row of a data.frame?
On Wed, Dec 17, 2003 at 08:27:41AM +0100, Sven C. Koehler wrote:> I am kind of new to R. > I would like to calculate the mean of the numbers of this expression: > > data(USArrests) > USArrests[row.names(M) == "Alabama",] > > class() tells me it's a ``data.frame,'' what I actually desire is to get > all numbers of a row as a vector or a list to let mean() calculate the mean > of the whole row. (I know this doesn't make sense with USArrests, I just > used it here instead of my very own data.frame.)rowMeans(USArrest) does what you want. In case you want to do soemthing else but compute the mean you will find this handy: apply(USArrests, 1, mean) here you can substitute "mean" by whatever function you'd like to apply to each row. cu Philipp -- Dr. Philipp Pagel Tel. +49-89-3187-3675 Institute for Bioinformatics / MIPS Fax. +49-89-3187-3585 GSF - National Research Center for Environment and Health Ingolstaedter Landstrasse 1 85764 Neuherberg, Germany