这个玩具示例允许我从用于线性回归的 mtcars
数据集中 react 性地更新我感兴趣的两个向量的 R 平方值。
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)
但是,我需要能够计算数据中几个不同组的 R 平方值(例如,使用“cyl”的级别)。添加
selectInput("group","Group","")
, observe({updateSelectInput(session,"group",choices=colnames(mtcars))})
和
detco.lm <- lm(mtcars[,input$xcol] ~ mtcars[,input$ycol], data=mtcars[,input$group])
没有产生期望的结果 - 我一直只得到单个 R 平方值。我正在寻找与输入组相对应的 R 平方值的表格或列表,例如
#Having selected "mpg" and "drat" as my x/y variables
cyl(4.00)=.4591
cyl(6.00)=.6679
cyl(8.00)=.1422
最佳答案
我认为这个 RStudio 博客 https://blog.rstudio.org/2015/09/29/purrr-0-1-0/ ,可能几乎与您在“ map 函数”部分中寻找的代码完全相同。您将需要 purrr
包。
编辑:粘贴该部分的代码,以防万一将来由于某种原因该链接发生变化。不要忘记 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
关于r - 按组计算多个 R 平方值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37417856/