[R] Function for ddply

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Tue Jul 24 09:58:40 CEST 2012

Not sure how to help you, because your example is not reproducible (does not run on my computer).

Some comments:

Avoid using the attach function. It is way better to use the data argument available in most functions.

The summarise function is designed for interactive use. You should probably write your own .FUN function if you are calling ddply within your own function.  See the help for ddply for examples of how to do that.
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
Sent from my phone. Please excuse my brevity.

Hutch Pollock <hutchpollock at gmail.com> wrote:

>Hello, all. I'm new to R and just beginning to learn to write
>functions. I
>know I'm out of my depth posting here, and I'm sure my issue is
>But here goes. I'm analyzing the American National Election Study
>looking at mean values of a numeric dep_var (environ.therm) across
>of a factor (partyid3). I use ddply from plyr and wtd.mean from Hmisc.
>nes requires a weight var (wt). I use Rcmdr's plotMeans to obtain a
>chart. The following code works:
>obj1 = ddply(nes, .(partyid3), summarise,
>  var = wtd.mean(environ.therm, wt))
>plotMeans(obj1$var, obj1$partyid3, error.bars="none")
>Here is what happens when I write and run the function, meanN:
> meanN=function(data,x,y,w=NULL)
>+  {obj1=ddply(data,.(x),summarise, var=wtd.mean(y,w))
>+  print(obj1)
>+  plotMeans(obj1$var, obj1$x, error.bars="none")
>+ }
> meanN(nes,partyid3,environ.therm,wt)
>Error in wtd.mean(y, w) : object 'w' not found
>I have assigned data, x, y, and w. I'm just learning this powerful
>Any help would be greatly appreciated.
>Hutch Pollock
>	[[alternative HTML version deleted]]
>R-help at r-project.org mailing list
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list