2

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

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 列,因为它不是数字。在更改背景颜色后,我无法找到一种方法来应用将值格式化为百分比数字的函数。

4

1 回答 1

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" )   
   }
}
于 2015-08-16T22:37:43.093 回答