[R] newbie - difficulty calling user defined function from by()

Uwe Ligges ligges at statistik.tu-dortmund.de
Wed Feb 4 20:05:31 CET 2009



Rixon, John C. wrote:
> Hi Folks:
>  
> I'm new to R and am having trouble calling a user-defined function
> within the by() function.  I have checked on-line help and the R
> documentation to no avail.  I have a data frame with a sample subset
> represented here:
>  
>> example.sample
>    ACCT_GROUP_DIM_KEY   MV_BASE TOT_DEBT TOT_EQTY
> 1        555586574850 1082576.3   685.00  2422.50
> 2        555586574850 1032994.2  2444.00  1724.00
> 3        555586574850  620471.0  3494.84  2712.59
> 4        555586574850  225047.4   592.21   514.17
> 5        555586574850  353844.5    48.25   396.28
> 6        555586574850  164043.6     0.00   204.14
> 7        555586574850  115792.4   436.25   669.60
> 8        555586574850 1299872.0  1794.21  1509.21
> 9        555586574851  100000.0     1.00   500.00
> 10       555586574851  100001.0     1.01   501.00
> 
> I am using the by() function to apply an aggregation on rows grouped by
> the key value.  A simple mean aggregation works as seen here:
> 
>> by (example.sample[, 2:4], example.sample["ACCT_GROUP_DIM_KEY"], mean)
> ACCT_GROUP_DIM_KEY: 555586574850
>    MV_BASE   TOT_DEBT   TOT_EQTY 
> 611830.169   1186.845   1269.061 
> ------------------------------------------------------------------------
> ------------------------- 
> ACCT_GROUP_DIM_KEY: 555586574851
>    MV_BASE   TOT_DEBT   TOT_EQTY 
> 100000.500      1.005    500.500 
> 
> I have defined a function that calculates a metric I want to apply
> against each group.  The function is:
> 
>> debt.eq
> function (x) {sum(
> (x["TOT_DEBT"]/x["TOT_EQTY"])*(x["MV_BASE"]/sum(x["MV_BASE"]))*100)}
> 
> When I call the function without any grouping I get:
> 
>> debt.eq (example.sample)
> [1] 88.1984
> 
> When I try to call my user-defined function in the by() function I get
> the following error:
> 
>> by (example.sample[, 2:4], example.sample["ACCT_GROUP_DIM_KEY"],
> debt.eq(example.sample))
> Error in FUN(X[[1L]], ...) : could not find function "FUN"


You probably want to call it like

  by (example.sample[, 2:4], example.sample["ACCT_GROUP_DIM_KEY"], debt.eq)


Uwe Ligges


> What is it I am doing wrong/missing here?  Thanks in advance,
> 
> John
> 
> ______________________________________________
> 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