How can we display few columns in percentage i.e instead of .2 display as 20% for each of the values in that particular column while other column remains as it is.
formattable::percent and scales::percent will apply but while rendering it is not visible.
library(DT)
ui <- basicPage(
h2("The mtcars data"),
DT::dataTableOutput("mytable")
)
server <- function(input, output) {
mydata <- mtcars
mydata$mpg <- formattable::percent(mydata$mpg/max(mydata$mpg))
mydata$cyl <- formattable::percent(mydata$cyl/max(mydata$cyl))
output$mytable = DT::renderDataTable({
data = mydata
})
}
shinyApp(ui, server)
There are few columns to be displayed as it is while few columns in percentage format.
Use DT::formatPercentage()
library(shiny)
library(DT)
library(dplyr)
ui <- basicPage(
h2("The mtcars data"),
DT::dataTableOutput("mytable")
)
server <- function(input, output) {
mydata <- mtcars %>%
mutate(mpg = mpg/max(mtcars$mpg),
cyl = cyl/max(mtcars$cyl))
output$mytable = DT::renderDataTable({
datatable(mydata) %>%
formatPercentage(c("mpg", "cyl"), 2)
})
}
shinyApp(ui, server)
2 Likes
Thanks for quick solution.
Is there a way to mention from mpg column to drat column, display as percentage and the rest as it is
Instead of this:
output$mytable = DT::renderDataTable({
datatable(mydata) %>%
formatPercentage(c("mpg", "cyl","disp","hp","drat","wt"), 2)
})
Can we declare this way ? using select(contains) or grepl ?
output$mytable = DT::renderDataTable({
datatable(mydata) %>%
formatPercentage(c("mpg":"wt"), 2)
})
You can use grep()
with regular expresions e.g. formatPercentage(grep("^m", x = names(mtcars)), 2)
or simply use positions instead of names e.g. formatPercentage(c(1:2), 2)
1 Like
Thanks @andresrcs . grep() seems to be vital. Would you mind sharing some resource to learn these ?
system
Closed
May 14, 2019, 4:10pm
6
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.