使用`tabulator`创建flextable时如何引用列,其中`col_keys`中包含`@`符号

rseugnpd  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(57)

我使用tabulator()创建了一个flextable,例如

Grp <- LETTERS[1:3]
Display <- c("Good", "Bad")
AgeGrp = c("00-11", "12-17")

dt <- expand.grid(Grp = Grp, Display = Display, AgeGrp = AgeGrp)
dt$outcome <- runif(12)

myformat <- function(z) {
    x <- sprintf("%.3f", z)
    x[is.na(z)] <- ""
    x
}

ft_dt <- tabulator(
  x = dt, rows = c("Grp", "Display"),
  columns = "AgeGrp",
  `Age` = as_paragraph(as_chunk(outcome, formatter = myformat))
) 

ft <- as_flextable(ft_dt)

字符串
这将导致col_keys,如"00-11@Age"
我还想有条件地重新格式化这些值,有些是百分比,有些是数字。
但是,以下代码将不起作用

compose(ft, i = ~Display=="Good", j = "00-11@Age", 
         value = as_paragraph(
           sprintf("%.0f", `00-11@Age`)
         ))


与下面的示例相比

ft_1 <- flextable(head(cars, n = 5), col_keys = c("speed", "dist"))
compose(
  x = ft_1, j = "speed",
  i = ~ dist > 9,
  value = as_paragraph(
    sprintf("%.3f%%", speed)
  )
)


如何引用包含@的列名?

bsxbgnwa

bsxbgnwa1#

我们得到的误差如下:

invalid format '%.0f'; use format %s for character objects

字符串
这里的问题是您使用了错误的列名,但这很容易修复。
tabulator_colnames()函数将显示可用于条件格式的名称。例如:

tabulator_colnames(ft_dt, columns = "outcome")
[1] "outcome@00-11" "outcome@12-17"


这里我们需要格式化显示的名为“00-11@Age”的列,但使用存储在“outcome@00-11”列中的值,该值不显示(但存储)。

compose(ft, i = ~Display=="Good", j = "00-11@Age", 
        value = as_paragraph(
          sprintf("%.0f", `outcome@00-11`)
        ))


x1c 0d1x的数据

相关问题