Printing table in R shiny

I would like to print a table like this in R shiny (A & B are the column names and observation 1 and observation2 are the row names of the table):

image

But the issue is that I am getting the following table as an output from R shiny. How should I format this table in R shiny?

image
Here's the R shiny code:

library(shiny)

ui <- fluidPage(

sidebarPanel(

numericInput("obs1", value = 2, min = 1, max = 4, label = "n1"),

numericInput("obs2", value = 2, min = 1, max = 4, label = "n2")

),

mainPanel(

  tableOutput("obs")

 

)

)

server <- function(input, output) {

output$obs <- renderTable({

number1 <- input$obs1

number2 <- input$obs2

N_metrics <- matrix(c(27432, 1715997, number1, number2), ncol = 2)

colnames(N_metrics) <- c("A", "B")

row.names(N_metrics) <- c ("observation1", "observation2")

N_metrics <- as.table(N_metrics)

N_metrics

})

}

shinyApp(ui, server)

Hi,

Removing the as.table casting and adding a rownames parameter to the renderTable method should fix the problem.

Here is the code:

library(shiny)

ui <- fluidPage(sidebarPanel(
  numericInput("obs1", value = 2, min = 1, max = 4, label = "n1"),
  numericInput("obs2", value = 2, min = 1, max = 4, label = "n2")
),
mainPanel(
  tableOutput("obs")
  )
)

server <- function(input, output) {
  output$obs <- renderTable({
    number1 <- input$obs1
    number2 <- input$obs2

    N_metrics <- matrix(c(27432, 1715997, number1, number2), ncol = 2)
    
    colnames(N_metrics) <- c("A", "B")
    row.names(N_metrics) <- c ("observation1", "observation2")
    
    N_metrics
  }, rownames = TRUE)
  
}

shinyApp(ui, server)

Also, check out the reprex package, it will help you writing better questions with a nice formatting of your code!

Regards,

2 Likes