[R] Divide all rows of a data frame by the first row.

Keith Weintraub kw1958 at gmail.com
Fri Jun 15 05:50:04 CEST 2012


Folks,

I call the function calcAmorts like so:
	calcAmorts(prevAm, amort, myDates)

Note that I use the package lubridate.

The last line where do.call is called to first divide all the rows by the first row and then rbind gives the following error:
    Error in do.call("rbind", apply(amortsByYears, 1, "/", amortsByYears[,  : 
    second argument must be a list

By contrast if I run 
do.call('rbind', apply(amortsByYears, 1, "/", amortsByYears[,1]))

On its own with any kind of numeric data.frame the call works fine. That is it divides every row in the data.frame by the first row.

Thanks so much for your time,
KW

_____________
My data:

myDates<-structure(c(1338523200, 1341115200, 1343793600, 1346472000, 1349064000, 
1351742400, 1354334400, 1357012800, 1359691200, 1362110400, 1364788800, 
1367380800, 1370059200, 1372651200, 1375329600, 1378008000, 1380600000, 
1383278400, 1385870400), class = c("POSIXct", "POSIXt"))



amort<-structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0333, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0333, 
0, 0, 0.0333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0.0333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0.0333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0357142857142857, 
0, 0, 0, 0, 0.0333, 0, 0, 0.0333, 0, 0, 0.0357142857142857, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0333, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0333, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0357142857142857, 0, 0, 0, 0, 0.0333, 
0, 0, 0.0333, 0, 0, 0.0357142857142857, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0.0333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0), .Dim = c(10L, 19L))

prevAm<-c(0, 0, 0, 0.0666, 0, 0.0666, 0.0666, 0, 0, 0)

calcAmorts<-function(prevAmort,  currAmorts, dates) {
   yrs<-year(as.Date(dates))
   currAmorts<-data.frame(yrs,t(currAmorts))
   amortsByYears<-aggregate(x = currAmorts, by = list(yrs), FUN = "sum")[,-c(1,2)]
   amortsByYears<-rbind(prevAmort, amortsByYears)
   amortsByYears<-(1-apply(amortsByYears, 2, cumsum))[-1,]

  do.call('rbind', apply(amortsByYears, 1, "/", amortsByYears[,1]))

}



More information about the R-help mailing list