在Shiny中使用反应函数需要有限的'xlim'值 [英] need finite 'xlim' values using reactive function in Shiny

查看:127
本文介绍了在Shiny中使用反应函数需要有限的'xlim'值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义文件输入来构建线性回归闪亮应用程序.我在Server.R中的反应式功能有问题.反应性函数 data 返回一个名为 qvdata 的数据帧.当在renderPlot中调用 data()并从 qvdata 绘图时,出现以下错误: "plot.window(...)中的错误:需要有限的'xlim'值".当我不使用反应函数并在renderPlot中进行计算时,不会发生错误.为什么是这样?我希望以后能够在其他渲染函数中调用此数据响应函数,以防止代码重复.

I'm trying to build a Linear regression Shiny app with a custom file input. I have a problem with the reactive function in Server.R. The reactive function data returns a data frame called qvdata. When data() is called in renderPlot and I plot from the qvdata I get the following error: "Error in plot.window(...):need finite 'xlim' values". When I do not use the reactive function and do the calculations in renderPlot the error does not occur. Why is this? I want later to be able to call this data reactive function in other render functions to prevent repetition in the code.

Server.R

library(shiny)
shinyServer(function(input, output) {
data<-reactive({
    inFile <- input$file1

    if (is.null(inFile))
        return(NULL)
    #takes in data (In my case .dat file)
    qvdata=read.table(inFile$datapath)
    names(qvdata)=c("H","Q")
    qvdata$Hlog=log(qvdata[,1])
    qvdata$Qlog=log(qvdata[,2])
    xbar=mean(qvdata$Hlog)
    ybar=mean(qvdata$Qlog)
    xdif=qvdata$Hlog-xbar
    ydif=qvdata$Qlog-ybar
    Sxy=sum(xdif*ydif)
    Sxx=sum(xdif*xdif)
    #point estimates of alfa and beta
    qvdata$b=Sxy/Sxx
    qvdata$a=ybar-qvdata$b*xbar
    qvdata
})

output$contents <- renderPlot({
    qvdata=data()
    t=seq(0,2,0.01)
    abline=qvdata$a+qvdata$b*t
    plot(qvdata$Hlog,qvdata$Qlog,type="p",pch=20,col="red")
    lines(t,abline,col="black")
})
})

ui.R

library(shiny)

shinyUI(fluidPage(
    titlePanel('Linear regression'),
    sidebarLayout(
        sidebarPanel(
            fileInput('file1', 'Choose file')   
        ),
        mainPanel(
            plotOutput('contents')

        )
    )
))

推荐答案

您的data函数在您闪亮的应用程序启动时首次运行.由于缺少输入文件,它将返回NULL.但是您的绘图功能不会测试其输入,因此在这种情况下等效于plot(NULL).如果您测试输入!is.null(),它应该可以工作:

Your data function runs the first time when your shiny app starts. Because the input file is missing it will return NULL. But Your plotting function doesn't test its input and is equivalent to plot(NULL) in this case. If you test for an input !is.null() it should work:

output$contents <- renderPlot({
    qvdata=data()
    if (!is.null(qvdata)) {
      t=seq(0,2,0.01)
      abline=qvdata$a+qvdata$b*t
      plot(qvdata$Hlog,qvdata$Qlog,type="p",pch=20,col="red")
      lines(t,abline,col="black")
    }
})

这篇关于在Shiny中使用反应函数需要有限的'xlim'值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆