【问题标题】:ShinyIncubator: Linear regression with matrixinputShinyIncubator:矩阵输入的线性回归
【发布时间】:2017-10-30 23:14:11
【问题描述】:

我很抱歉我是 R 的新手。我尝试自己处理这个问题有一段时间了,但我想不通,但我相信它很容易解决。

我想做一些统计分析(例如线性回归),让用户通过matrixInput自己输入数据。

library(shiny)
library(shinyIncubat)

df <- data.frame(matrix(c("0","0"), 1, 2))
colnames(df) <- c("x", "y")

ui <- pageWithSidebar(
  headerPanel('Enter data (x,y) here'),
  sidebarPanel(
    matrixInput('foo', 'Foo', data=df)
  ),
  mainPanel(
    verbatimTextOutput(outputId = "linreg")
  )
))

    server <- function(input,output) {

  lm1 <- reactive({lm(y~x,data=input$foo)})
  output$linreg <- renderPrint({summary(lm1())})

}

shinyApp(ui = ui, server = server)

我收到一个错误:“数据”必须是 data.frame,而不是矩阵或数组

【问题讨论】:

  • 你可以试试lm1 &lt;- reactive({lm(y~x, data=as.data.frame(input$foo))})

标签: r shiny regression


【解决方案1】:

正如 Stéphane Laurent 所说,您需要将 userInput 转换为数据框。显然,matrixInput 重命名了您的列名,因此您还需要在之后重命名新数据框的列,否则您的回归将失败。

library(shiny)
library(shinyIncubator)

df <- data.frame(matrix(c("0","0"), 1, 2))
colnames(df) <- c("x", "y") # you don't need this

ui <- pageWithSidebar(
  headerPanel('Enter data (x,y) here'),
  sidebarPanel(
    matrixInput('foo', 'Foo', data=df)
  ),
  mainPanel(
    verbatimTextOutput(outputId = "linreg")
  )
)

    server <- function(input,output) {

  lm1 <- reactive({

  lmdata<-as.data.frame(input$foo)
  names(lmdata)[1]<-'y'
  names(lmdata)[2]<-'x'

  reg<-summary(lm(y~x,data=lmdata))
  reg
  })

  output$linreg <- renderPrint({lm1()})
  # output$linreg <- renderPrint({print(input$foo)}) this way you can check how the userInput looks like

}

shinyApp(ui = ui, server = server)

【讨论】:

  • 非常感谢您花时间帮助新手!附言您的代码中缺少一个 ' ) ':# output$linreg &lt;- renderPrint({print(input$foo)}) 以防万一有人试图复制它。
  • 有没有办法结合names(lmdata)input$foo?我想构建类似inputData &lt;- reactive({as.data.frame(input$foo(names(input$foo)[1]&lt;-'y',names(input$foo)[2]&lt;-'x'))}) 的东西,但正如你所见,我不知道正确的语法,也找不到任何文档,我可以在其中弄清楚它是如何完成的。
  • 你的意思是像inputData&lt;-data.frame(y=input$foo[,1],x=input$foo[,2])这样的吗?
  • 我确实是这个意思!非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-07-12
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
相关资源
最近更新 更多