R formattable()防止删除具有相似名称的列

R formattable() prevent columns with similar name dropping

我正在为我的 shinyApp 使用很棒的包 formattable()。这是我遇到的问题的简化示例:

library(formattable)

df <- data.frame(
    ID = LETTERS[1:4], 
    `2018` = c(0.5, 0.9, 0.8, 0.4), 
    n = c(88, 44, 55, 66), 
    `2019` = c(0.9, 0.8, 0.7, 0.4), 
    n = c(78, 84, 54, 25))

names(df)[2] <- '2018'
names(df)[4] <- '2019'

formattable(
  df, align = c("l", "r", "l", "r", "l"),
  list(
    `2018` = function(x) percent(x, digits = 1),
    `2019` = function(x) percent(x, digits = 1)
  )
)

这很好用,但我希望将列 n.1 命名为 n。当我将 n.1 的列名重命名为 n 和 运行 相同的代码来创建 table 时,最后一列滴......似乎只有显示具有重复名称的任何列的第一列。

names(df)[5] <- "n"

formattable(
  df, align = c("l", "r", "l", "r", "l"),
  list(
    `2018` = function(x) percent(x, digits = 1),
    `2019` = function(x) percent(x, digits = 1)
  )
)

如何在列名称中同时显示 table 和 n

如果只是显示的问题,可以在第二个n列的名称中加上一个space(使用check.names = FALSE),如下:

df <- data.frame(ID     = LETTERS[1:4], 
                 `2018` = c(0.5,0.9,0.8,0.4), 
                 n      = c(88,44,55,66), 
                 `2019` = c(0.9,0.8,0.7,0.4), 
                 `n `   = c(78,84,54,25), 
                 check.names = FALSE)

df

formattable(df,
            align=c("l", "r", "l", "r", "l"),
            list(
              `2018` = function(x) percent(x, digits = 1),
              `2019` = function(x) percent(x, digits = 1)
            )
)

这将为您提供所需的输出:

希望您觉得它有用。