[R] Aggregate data frame across columns
arun
smartpink111 at yahoo.com
Wed Nov 7 19:04:50 CET 2012
HI,
Without data, it is a bit hard to know how your data looks like.
Anyway, try this:
set.seed(1)
dat2<-data.frame(matrix(sample(10:150,50,replace=TRUE),ncol=10))
names(dat2)<-c(paste0("20040",1:4),paste0("20050",1:3),paste0("20080",1:3))
library(reshape)
dat3<-melt(dat2)
dat3$variable<-gsub("(\\d{4}).*","\\1",dat3$variable)
tapply(dat3$value,dat3$variable,FUN=sum)
#2004 2005 2008
#1756 1094 1377
#or
with(dat3,aggregate(value,by=list(variable),sum))
# Group.1 x
#1 2004 1756
#2 2005 1094
#3 2008 1377
A.K.
----- Original Message -----
From: Keith Weintraub <kw1958 at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Wednesday, November 7, 2012 12:32 PM
Subject: [R] Aggregate data frame across columns
Folks,
I have a data frame with columns 200401, 200402, ..., 201207, 201208.
These represent years/months. What would be the best way to sum these columns by year? What about by quarter?
Thanks for your time,
KW
--
[[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list