2016-08-01 49 views
1

我是使用Shiny的新手,並且在將反應值添加到現有數據框時遇到了一些問題。將反應對象的值添加到現有數據框中作爲列

我有一個名爲CalculatedDistance的反應性對象,它計算閃亮應用上的輸入更改時的距離。我想在這個對象添加計算出的距離在數據幀的新列,但收到以下錯誤信息:

Error in CalculatedDistance[i] : object of type 'closure' is not subsettable

下面的代碼工作正常,直到我嘗試添加值新柱。

library('shiny') #allows for the shiny app to be used 

alldata <- iris 

#adds a column of a unique ID for each row 
alldata$ID <- 1:nrow(alldata) 

# UI 

ui<-fluidPage(
titlePanel("Explorer"), 
fluidRow(
     wellPanel(
     numericInput(inputId = "UserPetalLength", label="Input Petal Length", value = 0, step = 0.1), 
     numericInput(inputId = "UserPetalWidth", label="Input Petal Width", value = 0, step = 0.1)), 
     tableOutput('Table') 
)) 

#SERVER 
server<-function(input,output,session) 
{ 
CalculatedDistance<- reactive({ 
    calculatedDistance <- sqrt((alldata$Petal.Length-input$UserPetalLength)^2 + (alldata$Petal.Width-input$UserPetalWidth)^2) 
    }) 

alldata$distance<- NA 
nRows <- nrow(alldata) 
for (i in 1:nRows) 
{ 
    alldata$distance[i]= CalculatedDistance[i] 
} 
output$Table = renderTable(alldata) 

} 


#Run the Shiny App to Display Webpage 
shinyApp(ui=ui, server=server) 
+1

我想你錯過了'server'中的一組圓括號:'alldata $ distance [i] = CalculatedDistance()[i]'可以工作 –

+1

你也應該把這部分封裝在'reactive'中,以便它更新每次'UserPetalLength'變化 –

回答

0

這對我有效;我在server中做了一些修改,使其工作。

  • 裹的反應環境中添加到數據幀部分
  • 你的循環是沒有必要的,因爲CalculatedDistance返回一個載體,我們可以添加輕鬆
  • 增加了對數據幀{}output$Table
  • 轉換數據幀到數據表

#server.R 


    shinyServer(function(input,output,session) 
    { 
     CalculatedDistance<- reactive({ 
     calculatedDistance <- sqrt((alldata$Petal.Length-input$UserPetalLength)^2 + (alldata$Petal.Width-input$UserPetalWidth)^2) 
     calculatedDistance 
     }) 

     add_to_df <- reactive({ 
     alldata$distance<- NA 
     nRows <- nrow(alldata) 
     alldata$distance <- CalculatedDistance() 

     alldata 

     }) 

     output$Table <- renderTable({ 
     data.table(add_to_df()) 

     }) 

    }) 
+1

感謝這很好!必須安裝data.table包,但之後,一切都很好! – alexh

相關問題