【问题标题】:Conditional formatting FlexTable条件格式 FlexTable
【发布时间】:2017-07-16 18:33:19
【问题描述】:

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

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

【问题讨论】:

  • 它看起来和我期望的一样。 B 列是字符,因此要求小于或大于测试将使用“10”小于“2”的词法排序。如果你想测试他的数字部分而不是你需要 as.numeric 围绕 sub() 删除 %-sign。
  • 感谢您提出这个问题。我是pkg:ReportRs 的第一次用户。这看起来是一个很有前途的包。我过去使用过 R -> Excel -> PPT 的工作流程,成功率和失败率分别为 80:20。
  • 伟大而简单的解决方法!还有很多东西要学... ReporteRs 确实是一个很棒的软件包,对重复报告很有用。

标签: r reporters


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2021-12-22
    • 2018-09-02
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多