Home > Net >  In R Shiny, how to sum specified columns of a dataframe and output the results into a table?
In R Shiny, how to sum specified columns of a dataframe and output the results into a table?

Time:10-20

Here's an easy one to help make up for some of my other posts. I think it's easy but then again I didn't find solutions that work for me in my searches.

When running the below MWE code, how do I generate a simple table output that shows the sums of the 2 noted columns ('Nbr' and 'MOB')? The below gives me "Error in sum: invalid 'type' (character) of argument".

I'd like a table output (not a value embedded in a text string) because in the full App I'll be adding other sums to the output, building up a larger table.

MWE code:

library(shiny)

beta <- matrix(c(19,19,19,'2014-07','2014-08','2014-09',1,2,3), 
               nrow = 3, 
               ncol = 3, 
               dimnames = list(NULL,c("Nbr","Month","MOB")))
beta <- data.frame(beta)


ui <- fluidPage(
  tableOutput("summary")
  )

server <- function(input, output, session) {
  
  output$summary <- renderTable(c(sum(beta$Nbr,sum(beta$MOB))))
  
}

shinyApp(ui, server)

CodePudding user response:

The error (Error in sum(beta$MOB) : invalid 'type' (character) of argument) is telling you that you can't perform the function sum on a character vector. So you first have to convert to numeric, and then the error goes away.

beta <- matrix(c(19,19,19,'2014-07','2014-08','2014-09',1,2,3), 
               nrow = 3, 
               ncol = 3, 
               dimnames = list(NULL,c("Nbr","Month","MOB")))
beta <- data.frame(beta)

Add this here:

beta[c("Nbr","MOB")]<-sapply(beta[c("Nbr","MOB")],as.numeric)
  • Related