[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
>mundane.
>But here goes. I'm analyzing the American National Election Study
>(nes),
>looking at mean values of a numeric dep_var (environ.therm) across
>values
>of a factor (partyid3). I use ddply from plyr and wtd.mean from Hmisc.
>The
>nes requires a weight var (wt). I use Rcmdr's plotMeans to obtain a
>line
>chart. The following code works:
>
>attach(nes)
>obj1 = ddply(nes, .(partyid3), summarise,
>  var = wtd.mean(environ.therm, wt))
>print(obj1)
>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
>stuff.
>Any help would be greatly appreciated.
>
>Hutch Pollock
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>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.



More information about the R-help mailing list