Scott
Scott

Reputation: 313

Calculating multiple R squared values by groups

This toy example allows me to reactively update the R squared value for two vectors I'm interested in from the mtcars dataset for linear regression.

library(shiny)

ui <- fluidPage(
    selectInput("xcol","Select X Variable",""),
    selectInput("ycol","Select Y Variable",""),
  mainPanel(
    tableOutput("file"),
    verbatimTextOutput("detco")
  )
)

server <- function(input, output, session) {
  mtcars
  output$file <- renderTable({head(mtcars)})
  observe({updateSelectInput(session,"xcol",choices=colnames(mtcars))})
  observe({updateSelectInput(session,"ycol",choices=colnames(mtcars))})
  output$detco <- renderText({
    detco.lm <- lm(mtcars[,input$xcol] ~ mtcars[,input$ycol], data=mtcars)
    summary(detco.lm)$r.squared
  })
}

shinyApp(ui = ui, server = server)

However, I need to be able to calculate the R squared value for several different groups within the data (say, using the levels of "cyl" for example). Adding

selectInput("group","Group",""), observe({updateSelectInput(session,"group",choices=colnames(mtcars))}) and

detco.lm <- lm(mtcars[,input$xcol] ~ mtcars[,input$ycol], data=mtcars[,input$group]) 

doesn't yield the desired result - I keep getting just the single R squared value. I'm looking for a table or list of R squared values corresponding with the input group like

#Having selected "mpg" and "drat" as my x/y variables 
    cyl(4.00)=.4591    
    cyl(6.00)=.6679    
    cyl(8.00)=.1422

Upvotes: 2

Views: 1340

Answers (1)

Tyler Byers
Tyler Byers

Reputation: 131

I think this RStudio blog, https://blog.rstudio.org/2015/09/29/purrr-0-1-0/, may have almost exactly the code you're looking for in the "Map Functions" section. You'll need the purrr package.

Edit: Pasting the code from that section just in case, for whatever reason in the future, that link changes. Don't forget to install.packages('purrr')

mtcars %>%
  split(.$cyl) %>%
  map(~lm(mpg ~ wt, data = .)) %>%
  map(summary) %>%
  map_dbl("r.squared")
#>     4     6     8 
#> 0.509 0.465 0.423

Upvotes: 3

Related Questions