[R] Oh apply functions, how you confuse me

Patrick Burns pburns at pburns.seanet.com
Thu Sep 1 19:37:12 CEST 2011

I would suggest using a 'for' loop
rather than an apply function.  The
advantage is that you will probably
understand the loop that you write,
and it will run in roughly the same
amount of time as a complicated call
to an apply function that you don't

On 01/09/2011 18:11, LCOG1 wrote:
> Hi guys,
> I have a crap load of data to parse and have enjoyed creating a script that
> takes this data and creates a number of useful graphics for our area.  I am
> unable to figure out one summary though and its all cause I dont fully
> understand the apply family of functions.  Consider the following:
> #Create data
> Df..<-rbind(data.frame(Id=1:1008,Dir=rep(c("NB","NB","SB","SB"),252),Mph=runif(1008,0,65),
> Volume=runif(1008,0,19),Hour=rep(00,1008),Min5Break=rep(1:12,84),Day=rep(1,1008)),
> data.frame(Id=2009:2016,Dir=rep(c("NB","NB","SB","SB"),252),Mph=runif(1008,0,65),
> Volume=runif(1008,0,19),Hour=rep(01,1008),Min5Break=rep(1:12,84),Day=rep(2,1008)))
> #Example calc
> Results_<-list()
> #Sum Volume by 5 minute break by Day by Direction
> Results_$FiveMin.Direction<-tapply(Df..$Volume,list(Df..$Min5Break,Df..$Day,Df..$Hour,Df..$Dir),sum)
> The data is a snap shot of what im working with and I am trying to get to
> something similar to the last line where the volumes are summed.  What i
> want to do is to do a weighted average for the speed by 5 minute break.  So
> for all the speeds and volumes in a given hour of 5 minute break(12 per
> hour), i would want to
> sum(Volumes[1:12]*Speed[1:12]) / sum(Volumes[1:12]
> The output resembling the one from the above but having these weighted
> values.  I am assuming the sum function in the above would be replaced by a
> function doing the calculation but I am still not sure how to do this using
> apply functions, so perhaps this isnt the best option.
> Hope this is clear and hope you guys(and of course ladies) can offer some
> guidance.
> Cheers,
>   Josh
> --
> View this message in context: http://r.789695.n4.nabble.com/Oh-apply-functions-how-you-confuse-me-tp3784212p3784212.html
> Sent from the R help mailing list archive at Nabble.com.
> ______________________________________________
> 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.

Patrick Burns
pburns at pburns.seanet.com
twitter: @portfolioprobe
(home of 'Some hints for the R beginner'
and 'The R Inferno')

More information about the R-help mailing list