如何在R中创建一个函数来比较数据帧的连续偶数行和奇数行,并返回相同格式的数据帧?
如何创建一个函数来比较数据帧中连续的偶数行和奇数行,并返回相同的数据帧,其中满足条件的偶数行的值被格式化为红色 例如,我有以下数据框:如何在R中创建一个函数来比较数据帧的连续偶数行和奇数行,并返回相同格式的数据帧?,r,excel,dataframe,R,Excel,Dataframe,如何创建一个函数来比较数据帧中连续的偶数行和奇数行,并返回相同的数据帧,其中满足条件的偶数行的值被格式化为红色 例如,我有以下数据框: 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%)` =
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")
如果偶数行的值大于前面奇数行的同一列中的值,我想将偶数行的值(用于Excel中的输出)格式化为红色
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")
库(xlsx)
wb请显示您已经尝试过的代码,并显示您的预期输出。我不知道你说的“红色的”是什么意思,也不知道你想测试什么条件。太好了!非常感谢你