r语言 - 条件格式化FlexTable



我正在寻找一种使用百分比数字有条件地格式化弹性报表的方法。下面是一个小例子:

packs <- list("ReporteRs","scales")
lapply(packs,require,character.only = TRUE)
dat <- cbind.data.frame(rep("ABCD",2),c(0.07,0.11),c(0.03,0.01))
colnames(dat) <- c("A","B","C")
dat[,2] <- percent(dat[,2])
pp = pptx()
pp = addSlide(pp, "Title and Content")
datft = FlexTable(data = dat)
cname <- c("B","C") 
for (i in cname) {
   if (i=="B") {
   datft[dat[, i] <= 10, i] = cellProperties( background.color = "green" )
   datft[dat[, i] > 10, i] = cellProperties( background.color = "red" )
   } else if (i=="C") {
   datft[dat[, i] <= 0.02, i] = cellProperties( background.color = "green" )
   datft[dat[, i] > 0.02, i] = cellProperties( background.color = "red" )   
   }
}
pp = addFlexTable(pp, datft)
writeDoc(pp, paste(getwd(),"/example.pptx",sep=""))

对于列C可以正常工作,但显然不适用于列B,因为它不是数字。我想不出一个方法来应用一个函数,在改变背景颜色后将值格式化为百分比数字。

试试这个(在评论中有解释,但在测试之后):

for (i in cname) {
   if (i=="B") {
   datft[as.numeric( sub("%", "", dat[, i])) <= 10, i] = cellProperties( background.color = "green" )
   datft[ as.numeric( sub("%", "", dat[, i])) > 10, i] = cellProperties( background.color = "red" )
   } else if (i=="C") {
   datft[dat[, i] <= 0.02, i] = cellProperties( background.color = "green" )
   datft[dat[, i] > 0.02, i] = cellProperties( background.color = "red" )   
   }
}

相关内容

  • 没有找到相关文章

最新更新