Message-ID: <0D24B459-C8C5-4DF3-948E-603C4AFAAFA5@comcast.net>
Date: 2013-11-22T23:01:10Z
From: David Winsemius
Subject: averaging rows on a data.frame according to a factor
In-Reply-To: <CAMLNaBb5cPkh+p0XsWzsrEikA65z7kr2pUrn8CGAhvRxB29VjQ@mail.gmail.com>
On Nov 22, 2013, at 1:43 PM, john d wrote:
> Dear all,
>
> I apologize for the newbie question, but I'm stuck.
>
> I have a data frame in the following form:
>
> dat<-as.data.frame(cbind(c("a","a","a","b","b"), c(1,2,3,3,2),c(4,3,5,4,4)))
>
> I need a way to generate a new dataframe with the average for each factor.
> The result should look like:
Well, using the data,frame(cbind(...)) will ensure that you will NOT get factors, since cbind creates a matrix and that structure will not hold factors.
>
> res<-as.data.frame(cbind(c("a","b"), c(2,2.5),c(4,4)))
Ouch.
Look at ?tapply or ?aggregate.
Perhaps:
dat<-data.frame(facts= c("a","a","a","b","b"), nums1=c(1,2,3,3,2),nums2=c(4,3,5,4,4))
aggregate(dat[-1], dat[1], mean)
> Any help would be greatly appreciated.
>
> Jonathan
>
> [[alternative HTML version deleted]]
Newbie or not, you should still read the Posting Guide.
>
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
--
David Winsemius
Alameda, CA, USA