Reputation: 113
I have a list of dataframes, each with a common column name but other columns may differ. My goal is to format every but the common column as each df is shown in a shiny app. This is as far as I've gone:
library(shiny)
library(DT)
library(dplyr)
set.seed(101)
df1 <- data.frame(id = runif(10), col1 = rnorm(10), col2 = rnorm(10))
df2 <- data.frame(id = runif(10), col1 = rnorm(10), col3 = rnorm(10))
df3 <- data.frame(id = runif(10), col3 = rnorm(10), col4 = rnorm(10))
df <- list(data1 = df1, data2 = df2, data3 = df3)
ui <- fluidPage(
fluidRow(
column(3, selectInput('select', 'Choose dataframe: ', choices = c('data1', 'data2', 'data3'),
selected = 1)),
column(9, DTOutput('table'))
)
)
server <- function(input, output) {
selected <- reactive({
input$select
})
col_names <- c('col1', 'col2', 'col3', 'col4')
output$table <- renderDT(
df[[selected()]] %>% formatStyle(names(.)[names(.) %in% col_names], backgroundColor = 'yellow'),
options = list(pageLength = 15))
}
shinyApp(ui=ui,server=server)
And here is the error I get in the console:
Warning: Error in name2int: You specified the columns: col1, col2, but the column names of the data are [No stack trace available]
How can I get formatStyle to work with those variable column names?
Upvotes: 1
Views: 765
Reputation: 887661
Consider changing it to datatable
server <- function(input, output) {
selected <- reactive({
input$select
})
col_names <- c('col1', 'col2', 'col3', 'col4')
output$table <- DT::renderDT(
{dat <- df[[selected()]]
nm1 <- intersect(names(dat), col_names)
DT::datatable(dat, options = list(pageLength = 15)) %>%
formatStyle(nm1, backgroundColor = 'yellow')
}
)
}
shinyApp(ui=ui,server=server)
-output
Upvotes: 0