[R] Error using ddply inside user-defined function

Brian Diggs diggsb at ohsu.edu
Tue Aug 7 23:34:12 CEST 2012


A few comments in-line below

On 8/7/2012 1:53 PM, Jennifer Sabatier wrote:
> PROV.PM.FBCTS <- c(0.00 ,0.00, 33205.19, 25994.56, 23351.37, 26959.56
> ,27632.58, 26076.24, 0.00,     0.00 , 6741.42, 18665.09 ,18129.59 ,21468.39
> ,21294.60 ,22764.82, 26076.73)
> FBCTS.INV.TOT <- c(0 ,      0,  958612,  487990,  413344,  573347,  870307,
> 552681 ,      0, 0 , 163831 , 400161 , 353000,  358322 , 489969,  147379,
> 1022769)
> FBCTS.REC.TOT <- c(0   ,    0, 1638818  ,297119 , 299436  ,414164 , 515735,
>   529001   ,    0, 0 , 427341 , 625893  ,437854 , 407091,  425119 ,   8663,
>        0)
> MECH.NAME <- c("Mechanism A","Mechanism A","Mechanism A","Mechanism
> A","Mechanism A","Mechanism A","Mechanism A","Mechanism A", "Mechanism
> B","Mechanism B","Mechanism B","Mechanism B","Mechanism B","Mechanism
> B","Mechanism B","Mechanism B","Mechanism B",)

Line breaks have messed up this data and there is an extra comma at the 
end of MECH.NAME

> vn <- data.frame(MECH.NAME, PROV.PM.FBCTS, FBCTS.INV.TOT, FBCTS.REC.TOT)

It is easier to just give the final object. See the output of dump("vn", 
file="")

> # create function
>
> allocation <- function(vr1, vr2, vr3)
> {
>
> d <- ddply(vn, "MECH.NAME", summarise, SUM = vr1 + vr2 + vr3)

ddply is looking for a column named vr1 (etc.), not a column whose name 
is that of the character value of the variable vr1. There is not a 
straightforward way to do this with summarise, but you can use something 
like

function(DF) {
     data.frame(SUM = DF[[vr1]] + DF[[vr2]] + DF[[vr3]])
}

> vn <- merge(vn, d, by.x="MECH.NAME", by.y="MECH.NAME", all=T)
> new <- (vr1+vr2+vr3) / vn$SUM
> return(new)
>
> }
>
> # run function
>
> vn$PROV.PM.FBCTS <- allocation(PROV.PM.FBCTS, FBCTS.INV.TOT, FBCTS.REC.TOT)
>
> Here's the error:
>
>> >vn$PROV.PM.FBCTS <- allocation(PROV.PM.FBCTS, FBCTS.INV.TOT,
> FBCTS.REC.TOT)
> Error in eval(expr, envir, enclos) : object 'vr1' not found
>
>
> # If I pull the calculations out of the function it works:
>
>
> d <- ddply(vn, "MECH.NAME", summarise, SUM = sum(PROV.PM.FBCTS,
> FBCTS.INV.TOT, FBCTS.REC.TOT))

Note that sum(a,b) is not the same as a+b.

> vn <- merge(vn, d, by.x="MECH.NAME", by.y="MECH.NAME", all=T)
> vn$PROV.PM.FBCTS <- (PROV.PM.FBCTS +  FBCTS.INV.TOT + FBCTS.REC.TOT) /
> vn$SUM
>
>


-- 
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University



More information about the R-help mailing list