2017-10-09 88 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