Hello R community, I am computing weighted average statistic by using ddply function:
My data set is: N1 T1 S1 I1 C1 FY-4 ROE11 EPS11 MKT11 N1 T1 S1 I1 C1 FY-3 ROE12 EPS12 MKT12 N1 T1 S1 I1 C1 FY-2 ROE13 EPS13 MKT13 N1 T1 S1 I1 C1 FY-1 ROE14 EPS14 MKT14 N1 T1 S1 I1 C1 FY0 ROE15 EPS15 MKT15 N1 T1 S1 I1 C1 FY1 ROE16 EPS16 MKT16 N1 T1 S1 I1 C1 FY2 ROE17 EPS17 MKT17 N2 T2 S2 I2 C2 FY-4 ROE21 EPS21 MKT21 N2 T2 S2 I2 C2 FY-3 ROE22 EPS22 MKT22 N2 T2 S2 I2 C2 FY-2 ROE23 EPS23 MKT23 N2 T2 S2 I2 C2 FY-2 ROE24 EPS24 MKT24 N2 T2 S2 I2 C2 FY0 ROE25 EPS25 MKT25 N2 T2 S2 I2 C2 FY2 ROE26 EPS26 MKT26 N2 T2 S2 I2 C2 FY2 ROE27 EPS27 MKT27 with colnames: (Name,Ticker,Sector,Industry,Country,Year,ROE,EPS,MKTCAP) I want to compute 1) Weighted ROE based on Sector and Fiscal Year. For firm N1 of Sector S1 and Fiscalyear FY-3 weight is MKT1 / SUM(MKT, where Sector = S1, Fiscalyear FY-3) 2) Weighted ROE based on Country and Fiscal Year. For firm N1 of Country C1 and Fiscalyear FY-3 weight is MKT1 / SUM(MKT, where Country = C1, Fiscalyear FY-3) 3) Weighted ROE based on Country, Sector and Fiscal Year. For firm N1 of Country C1, Sector S1 and Fiscalyear FY-3 weight is MKT1 / SUM(MKT, where Country = C1, Sector = S1, Fiscalyear FY-3) 4) Weighted ROE based on Country, Industry and Fiscal Year. For firm N1 of Country C1, Industry I1 and Fiscalyear FY-3 weight is MKT1 / SUM(MKT, where Country = C1, Industry = I1, Fiscalyear FY-3) I tried using ddply function: ddply (dataread , .(Sector, FISCALYEAR), summarise, WROE=wavg(ROE, MKTCAP))) where wavg <- function(x, wt) x %*% wt/sum(wt) but this doesn't give me the right answer. I could try subseting the data into different sectors and compute the weighted average which doesn't look like an elegant solution and would defeat the purpose of ddply I coudn't think of properly using melt and cast functions to solve this issue. Any help will be highly appreciated. Thanks and Regards, Punit ______________________________________________ R-help@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.