I am a new member to this community and am having trouble calculating the weighted average of my dataset. Granted, I am a beginner in R barely scratching the surface of R and am trying to learn it as much as I can.

I know what I want the outcome to be, I don't know where to start with the commands. Any help is greatly appreciated! Criticism is more than welcome.

Here's my problem/hurdle:

I would like to display the weighted average of each security within its sector level, sorted by the composite rating (A, AA, BBB). For example:

Weighted average of Industrials (Sector Level 2) in Corporate (Sector Level 1).

Weighted average of Automotive (Sector Level 3) in Industrials (Sector Level 2).

Weighted average of each security in Auto Parts & Equipment (Sector Level 4) in Automotive (Sector Level 3) and so on.

I have no idea what commands would accomplish my goal. I am very open to suggestions and ideas. Thank you in advance.

Here's the code I have written so far, and you will find a link (dropbox) to my .csv document containing the dataset (if this is not the preferred method of sharing data, please let me know). I have formatted the data to only use the relevant information, as seen in the code below.

Link to the .csv file: Dropbox file link

Code:

```
mkt <- read.csv
library(plyr)
library(lubridate)
divisor <- ddply(mkt,.(Sector.Level.2,Sector.Level.3,Sector.Level.4,year,Composite.Rating),summarize,amt=sum(Face.Value))
divisor$id <- paste(divisor$Sector.Level.4,divisor$year,sep="")
subind.year <- divisor[,c("id","amt")]
mkt$Maturity <- mdy(as.character(mkt$Maturity))
mkt$year <- year(mkt$Maturity)
mkt$Composite.Rating <- gsub("^A1","A",mkt$Composite.Rating)
mkt$Composite.Rating <- gsub("^A2","A",mkt$Composite.Rating)
mkt$Composite.Rating <- gsub("^A3","A",mkt$Composite.Rating)
mkt$Composite.Rating <- gsub("^AA1","AA",mkt$Composite.Rating)
mkt$Composite.Rating <- gsub("^AA2","AA",mkt$Composite.Rating)
mkt$Composite.Rating <- gsub("^AA3","AA",mkt$Composite.Rating)
mkt$Composite.Rating <- gsub("^BBB1","BBB",mkt$Composite.Rating)
mkt$Composite.Rating <- gsub("^BBB2","BBB",mkt$Composite.Rating)
mkt$Composite.Rating <- gsub("^BBB3","BBB",mkt$Composite.Rating)
#head(mkt$Composite.Rating,50)
table <- ddply(mkt,.(Sector.Level.2,Sector.Level.3,Sector.Level.4,year,Composite.Rating),summarize,
m.ytw = round(mean(Yield.to.Worst),digits=2),
m.ytm = round(mean(Effective.Yield),digits=2),
m.dtw = round(mean(Duration.To.Worst),digits=2),
m.ed = round(mean(Effective.Duration),digits=2),
m.oas = round(mean(OAS.vs.Govt),digits=2),
m.avglife = round(mean(year),digits=2),
num = length(Sector.Level.3),
amt=sum(Face.Value))
```