r - 使用R Shiny中的动态输入建立线性回归

标签 r shiny

我正在尝试使用线性回归构建一个简单的 Shiny 应用程序,该应用程序允许用户选择在lm()函数中使用的自变量和因变量,并最终绘制出一些图表。我目前停留在将输入传递给Shiny服务器端的lm()函数,并能够打印出回归摘要。谁能协助我解决我的逻辑/代码出现问题的地方。下面是代码

library(shiny)
library(data.table)

RegData <- as.data.table(read.table("/home/r2uphp/ShinyApps/IRViews/RegData.tsv", header = TRUE, stringsAsFactors = FALSE))

ui <- fluidPage(
  headerPanel("Regression and Time Series Analysis"), 
  sidebarPanel(
    p("Select the inputs for the Dependent Variable"),
    selectInput(inputId = "DepVar", label = "Dependent Variables", multiple = FALSE, choices = list("AvgIR", "YYYYMM", "SumCount", "AvgLTV", "AvgGFEE", "AvgRTC", "Date")),
    p("Select the inputs for the Independent Variable"),
    selectInput(inputId = "IndVar", label = "Independent Variables", multiple = FALSE, choices = list( "SumCount", "AvgIR", "YYYYMM", "AvgLTV", "AvgGFEE", "AvgRTC", "Date"))
  ),
  mainPanel(
    verbatimTextOutput(outputId = "RegSum"),
    verbatimTextOutput(outputId = "IndPrint"),
    verbatimTextOutput(outputId = "DepPrint")
    #plotOutput("hist")
  )
)

server <- function(input, output) {

    lm1 <- reactive({lm(paste0(input$DepVar) ~ paste0(input$IndVar), data = RegData)})

    output$DepPrint <- renderPrint({input$DepVar})
    output$IndPrint <- renderPrint({input$IndVar})
    output$RegSum <- renderPrint({summary(lm1())})

}

shinyApp(ui = ui, server = server)

This is the result of the shinyapp

这是我正在使用的样本数据集:
     YYYYMM      AvgIR SumCount    AvgLTV     AvgGFEE   AvgRTC       Date
 1: 2015-10 0.04106781   180029 0.7531805 0.002424778 319.6837 2015-10-01
 2: 2015-11 0.04036154   160061 0.7380383 0.002722529 312.6314 2015-11-01
 3: 2015-12 0.04001407   145560 0.7392874 0.002425912 313.0351 2015-12-01
 4: 2016-01 0.04034078   147693 0.7396932 0.002600640 315.0238 2016-01-01
 5: 2016-02 0.04055688   142545 0.7345160 0.002449523 310.3950 2016-02-01

提前致谢!

最佳答案

您只需要正确构建公式即可。我不确定paste0会做什么,但这是一个更好的方法

lm1 <- reactive({lm(reformulate(input$IndVar, input$DepVar), data = RegData)})
reformulate()命令将为您构建正确的公式(请注意,自变量在函数中排在首位。

关于r - 使用R Shiny中的动态输入建立线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43102554/

相关文章:

r - 更新 Shiny 的 react 数据帧会出现替换错误

r - Shiny:如何在禁用操作按钮的情况下启动应用程序?

r - 在 Shiny 中的 selectInput() 中应该怎么写?

r - 使用大内存在 R 中处理大于物理 RAM 的数据?

r - 分类变量(因子)与虚拟变量的区别

r - 在 MNIST 数字识别数据集上表现不佳

r - 整形表的性能

css - DT Shiny 不同的自定义列标题按列

R Shiny - 输出汇总统计

mysql - { : task 1 failed - "could not find function "dbGetQuery""中的 FOREACH 循环错误