条件格式化FlexTable

时间:2015-08-16 18:33:06

标签: r reporters

我正在寻找一种方法,使用百分比数据有条件地使用ReporteRs格式化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列,因为它不是数字。在找到backgroundcolor之后,我无法找到一种方法来应用将值格式化为百分比数字的函数。

1 个答案:

答案 0 :(得分:2)

试试这个(在评论中有解释但是经过测试):

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" )   
   }
}