HI, If you have more than one observation per month, you could do this: dat1<-read.table(text=" Year Month Sales Customer 2011 Jan 150 35 2011 Jan 125 40 2011 Feb 130 45 2011 Feb 135 25 2012 Jan 100 25 2012 Jan 150 35 2012 Feb 118 45 2012 Feb 120 30 2012 Mar 130 43 2012 Mar 125 35 ",sep="",header=TRUE,stringsAsFactors=FALSE) res<-aggregate(.~Year+Month,data=dat1,mean) within(res,{Avrev<-Sales/Customer}) # Year Month Sales Customer Avrev #1 2011 Feb 132.5 35.0 3.785714 #2 2012 Feb 119.0 37.5 3.173333 #3 2011 Jan 137.5 37.5 3.666667 #4 2012 Jan 125.0 30.0 4.166667 #5 2012 Mar 127.5 39.0 3.269231
A.K. ----- Original Message ----- From: Paolo Donatelli <donatellipa...@gmail.com> To: r-help@r-project.org Cc: Sent: Wednesday, January 9, 2013 11:02 AM Subject: [R] Basic loop programming Hi all, newbie question: I am trying to set up a very simple loop without succeeding. Let's say I have monthly observation of two variables for a year - Sales_2012_01, Sales_2012_02, Sales_2012_03, .... (total sales for jan 2012,feb 2012, etc.) - Customers_2012_01, Customers_2012_02, .... (total number of customers for jan 2012, etc.) and I want to create new monthly variables in order to compute revenues per customers: Av_revenue_2012_01 = Sales_2012_01 / Customers_2012_01 Av_revenue_2012_02 = Sales_2012_02 / Customers_2012_02 ... how can I proceed? In other programming language I used just to write something like for (i in list("01","02, ..., "12") { Av_revenue_2012_'i' = Sales_2012_'i' / Customers_2012_'i' } but in R it seems not to work like that. Further, and correct me if I am wrong, I cannot use simple (i in 1:12) since I have a 0 digit in front of the single-digit months. thanks in advance for your help ______________________________________________ R-help@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. ______________________________________________ R-help@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.