Luc
Luc

Reputation: 958

R formattable() prevent columns with similar name dropping

I am using the wonderful package formattable() for my shinyApp. Here is a simplified example of the issue I have:

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

enter image description here

This works well, but I would like the column n.1 to be named n. When I rename the column name of n.1 to n, and run the same code to create the table, the last column drops of... It seems that only the first column of any columns with duplicate names are displayed.

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

How can I present the table with both n in the column names?

Upvotes: 2

Views: 250

Answers (1)

Taher A. Ghaleb
Taher A. Ghaleb

Reputation: 5240

If it's just a matter of display, you may add a space to the name of the second n column (with the use of check.names = FALSE), as follows:

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

This will give you the desired output:

output

Hope you find it useful.

Upvotes: 2

Related Questions