Q:

How to create a function in R that compares consecutive even and odd rows of a dataframe and returns the same formatted data frame?

How can I create a function that compares consecutive even and odd rows of a dataframe, and returns the same dataframe where the values of the even rows that satisfy the condition are formatted with the red ones?
For example, I have the following data frame:
structure(list(`uc.LRp(5%)` = c(0.8364, 0.1678, 0.6776, 0.6852, 
0.6776, 1, 1, 0.8384), `cc.LRp(5%)` = c(0.9673, 0.3091, 0.9155, 
0.8415, 0.9155, 0.8082, 0.9703, 0.9258), `DQp(5%)` = c(0.1681, 
0.1128, 0.0904, 0.549, 0.1073, 0.7182, 0.1814, 0.094), `AE(5%)` = c(0.96, 
1.28, 0.92, 1.08, 0.92, 1, 1, 1.04), `uc.LRp(1%)` = c(0.663, 
0.3966, 0.3966, 0.6414, 0.663, 0.6414, 0.6414, 0.3315), `cc.LRp(1%)` = c(0.8454, 
0.6319, 0.6319, 0.8687, 0.8454, 0.8687, 0.8687, 0.6128), `DQp(1%)` = c(0.8981, 
2e-04, 0.0019, 0.997, 0.8944, 0.9927, 0.9793, 0.984), `AE(1%)` = c(1.2, 
1.4, 1.4, 0.8, 1.2, 0.8, 0.8, 0.6)), .Names = c("uc.LRp(5%)", 
"cc.LRp(5%)", "DQp(5%)", "AE(5%)", "uc.LRp(1%)", "cc.LRp(1%)", 
"DQp(1%)", "AE(1%)"), row.names = c("sGARCH - norm", "MS sGARCH - norm", 
"eGARCH - norm", "MS eGARCH - norm", "gjrGARCH - norm", "MS gjrGARCH - norm", 
"sGARCH - std", "MS sGARCH - std"), class = "data.frame")

I want to format the values (for output in Excel) of the even rows in red if these values are greater than the values in the same column of the preceding odd row

A:

Here is a quick and dirty example using the 'xslx' package.
library(xlsx)
wb <- createWorkbook()
sheet <- createSheet(wb,sheetName="test")
rows  <- createRow(sheet,rowIndex=1:(1+nrow(df)))
cells <- createCell(rows,colIndex=1:(1+ncol(df)))

t <- mapply(setCellValue, cells[2:(1+nrow(df)),1], row.names(df))
setColumnWidth(sheet,1,max(nchar(row.names(df))))
m <- max(nchar(colnames(df)))
for (i in 1:ncol(df)) {
  setColumnWidth(sheet,1+i,m)
  setCellValue(cells[[1,1+i]],colnames(df)[i])
  mapply(setCellValue, cells[2:(1+nrow(df)),1+i], df[[i]])  
  for (j in 1:(nrow(df)/2))
    if (df[2*j,i]>df[2*j-1,i])
        setCellStyle(cells[[1+2*j,1+i]],CellStyle(wb,fill=Fill(foregroundColor="red")))
}
saveWorkbook(wb,"1.xlsx")

 

