mapply & gapply

23 views
Skip to first unread message

hol...@gmail.com

unread,
Aug 22, 2008, 12:25:46 PM8/22/08
to Forest-R
The apply() functions are very useful in R, but due to my years using
SAS I have hard time getting my mind around most of them. Two apply()
function that are rarely mentioned and I have found quite useful are
mapply() and gapply(). mapply() is useful for avoiding for loops and
applying a function that contains an if statement across a dataframe.
For example,

get.month = function(dayofyear) {
last.day <- c(31,59,90,120,151,181,212,243,273,304,334,365)
first.day <- c( 1,32,60, 91,121,152,182,213,244,274,305,335)
for (i in 1:12) {
if (dayofyear <= last.day[i]) {
month <- i
day <- dayofyear - first.day[i] + 1
break}}
return(month=month)}

climate$month<-mapply(get.month,climate$yday)

The other is gapply() in the nlme() library, which works similar to a
by statement in SAS. The data must be grouped. For example,

library(nlme)
climate<-groupedData(tday~yday|STAND/YEAR/month,data=climate)
avg.tmax<-as.vector(gapply(climate,which="tmax",function(x)
round(mean(x),2)))

This would return a vector of average maximum daily temperatures for
each month within a year within a stand.

greg.j...@weyerhaeuser.com

unread,
Aug 22, 2008, 1:08:08 PM8/22/08
to Forest-R
Here's a version of the get.month function that runs in 46.6% of the
runtime:

get.month <- function( dayofyear )
{
last.day <- c(31,59,90,120,151,181,212,243,273,304,334,365)
first.day <- c( 1,32,60, 91,121,152,182,213,244,274,305,335)
month <- c(1:12)[dayofyear >= first.day & dayofyear <= last.day]
month

greg.j...@weyerhaeuser.com

unread,
Sep 4, 2008, 1:31:57 PM9/4/08
to Forest-R
To generalize the get.month function so that it accepts a vector of
days (the original accepted a scalar), use the following function:

get.month <- function( dayofyear )
{
last.day <- c(31,59,90,120,151,181,212,243,273,304,334,365)
first.day <- c( 1,32,60, 91,121,152,182,213,244,274,305,335)
month <- unlist(lapply( dayofyear, function(x){ c(1:12)[x>=
first.day & x <= last.day] } ))
month
Reply all
Reply to author
Forward
0 new messages