2017-10-09 117 views
0

对于R闪亮我很新,所以一直无法找到本网站发布的类似问题的解决方案。我正在尝试阅读并使用用户提供给R shiny的输入来生成输出。基于R中的动态用户输入打印输出Shiny

我想创建一个简单的GUI,其中用户选择一个人的名字(从下拉菜单),然后输入他/她的体重。如果身高高于某个阈值,输出建议为“增加体重”,否则为“体重减轻”。

一切都似乎是做工精细,除了从Server.R文件以下错误:

Error in `$.shinyoutput`(output, value_weight) : 
Reading objects from shinyoutput object not allowed 

我怎样才能读取和一个if-then-else条件使用变量“value_weight”?

Main.R

library(shiny) 
runApp() 

Server.R

function(input, output) { 

# You can access the value of the widget with input$select, e.g. 
output$value_name <- renderPrint({ input$select }) 
output$value_weight <- renderPrint({ input$num }) 

if(output$value_weight > 150) 
{ 
    output$value_recommendation <- "Loose Weight" 
} 
else{ 
    output$value_recommendation <- "Gain Weight" 
} 

} 

UI.R

names_list <- list("Adam", "Jenna","Peter") 

fluidPage(
selectInput("select", label = h3("Select Name"), choices = names_list, selected = 1), 

hr(), 
fluidRow(column(3, verbatimTextOutput("value_name"))), 
numericInput("num", label = h3("Enter Weight"), value = 0), 

hr(), 
fluidRow(column(3, verbatimTextOutput("value_weight"))), 

hr(), 
fluidRow(column(3, verbatimTextOutput("value_recommendation"))) 

    ) 

回答

1

在你的代码的问题是该行

if(output$value_weight > 150) 

一般来说,output s为只写在服务器对象,而input s为只读。如果你用input$num替换output$value_weight,一切都应该正常工作。您还需要为输出使用渲染函数:在此例中为renderPrintrenderText(有关这两个渲染函数之间的区别,请参阅文档)。

## server.R 
function(input, output) { 
    # You can access the value of the widget with input$select, e.g. 
    output$value_name <- renderPrint({ input$select }) 
    output$value_weight <- renderPrint({ input$num }) 

    output$value_recommendation <- renderPrint({ 
    if(input$num > 150) 
     "Loose Weight" 
    else 
     "Gain weight" 
    }) 
} 

另一种方式来做到这一点是使用调用该函数reactive

## server.R 
function(input, output) { 
    # You can access the value of the widget with input$select, e.g. 
    output$value_name <- renderPrint({ input$select }) 
    value_weight <- reactive({ input$num }) 
    output$value_weight <- renderPrint({ value_weight() }) 

    output$value_recommendation <- renderPrint({ 
    if(value_weight() > 150) 
     "Loose Weight" 
    else 
     "Gain weight" 
    }) 
} 
0

使用 'renderText' 解决了这个问题!

Server.R

function(input, output) 
{ 

    output$value_market <- renderPrint({ input$select }) 
    output$value_demand <- renderPrint({ input$num }) 


    output$value_recommendation <- renderText({ 
    if(input$num > 150) 
    { 
    print("Loose Weight") 
    } 
    else{ 
    print("Gain Weight") 
    } 
    }) 
} 
+0

哦!只是看到你自己解决了。希望我的回答能让你更深入地了解*为什么*你遇到了这个特定的错误信息。 –

+0

是的!我已经接受你的答案!谢谢 :) – Batool