On Tue, 2011-03-15 at 07:24 -0700, Carl Nim wrote: > I am trying to calculate monthly means by year of phosphates and nitrates > from a multi year data set. Can anybody help me out with the most effective > way to do this? > > My data looks like this: > > Collection_Date Test.Name Value > 2000-01-24 17:00:00 Phosphate 0.108 > 2000-01-24 17:00:00 Nitrate 0.037 > 2001-11-12 08:45:00 Phosphate 0.45 > ... > > > Thanks and sorry for the blatantly "newbie" question.
Let's say you have a data.frame, mydata, with the above data. Then you could write a function mymean <- function(year, month, substance) { mysub <- subset(mydata, format(as.PPSIXlt.date(Collection_Date), "%Y") == year, format(as.POSIXlt.date(Collection_Date), "%b") == month, Test.Name == substance) return(mean(mysub$value)) } Then you need to apply this function to every combination of year, month and substance in your data.frame. You can do this by M <- expand.grid(2000:2010, month.abb, c("Phosphate", "Nitrate")) meanValues <- apply(M, 1, mymean(myRowEntry[1], myRowEntry[2], myRowEntry[3]) In the end you can put the result together with M, i.e. M <- cbind(M, meanValues) > > > > > [[alternative HTML version deleted]] > > ______________________________________________ > 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. -- Daniel Kaschek Physikalisches Institut, Freiburg Hermann-Herder-Str. 3 79104 Freiburg Office: Westbau, 02020 Phone: +49-761-203-8531
signature.asc
Description: This is a digitally signed message part
______________________________________________ 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.