2014-11-03 43 views
2

我想弄清楚如何讓R通過與其他JavaScript元素的閃亮交互,我猜想通過server.R服務定製的閃亮對象(理想情況下,json格式化?)至ui.R,然後轉換爲javascript數組。我的工作正在進行代碼:傳遞json /數據到一個JavaScript對象與閃亮

server.R

library(shiny) 

shinyServer(
    function(input, output) { 
    output$species_table <- renderTable({ iris[iris$Species == input$species,] }) 
    output$json <- RJSONIO::toJSON(iris[iris$Species == input$species,], byrow=T, colNames=T) # error line 
    } 
) 

ui.R

require(shiny) 
specs = as.character(unique(iris$Species)) 
names(specs) = specs 

pageWithSidebar(
    headerPanel("minimal json handling example"), 
    sidebarPanel(selectInput("species", "Species", specs)), 
    mainPanel(
    tableOutput("species_table") 
) 
) 

它返回服務器錯誤:

Error in .getReactiveEnvironment()$currentContext() : 
    Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside 
a reactive expression or observer.) 

..因爲這顯然是錯誤的做法。沒有服務器.R的行output$json <- ...的結果工程和looks like this,所以其餘的代碼是好的。但我也希望以某種方式獲得json(或任何其他格式),並觸發後續的javascript操作,以數組對象的形式讀取它。感謝任何指點,並提前道歉,如果我的描述不清楚。

回答

2

所以,這個錯誤通常意味着你需要在某些東西上包裝reactive({}),在這種情況下你的toJSON命令。這工作,並顯示JSON數據。

ui.r

require(shiny) 
specs = as.character(unique(iris$Species)) 
names(specs) = specs 

pageWithSidebar(
    headerPanel("minimal json handling example"), 
    sidebarPanel(selectInput("species", "Species", specs)), 
    mainPanel(
    #tableOutput("species_table") 
    textOutput("json") 
) 
) 

server.r

library(shiny) 

shinyServer(
    function(input, output) { 
    output$species_table <- renderTable({ iris[iris$Species == input$species,] }) 
    output$json <-reactive({ RJSONIO::toJSON(iris[iris$Species == input$species,], 
     byrow=T, colNames=T) })# error line 
    } 
) 
+0

感謝約翰,將檢查這個明天。你有什麼想法,我怎麼能讀取作爲JavaScript對象以某種方式,以便與非閃亮的腳本集成? – geotheory 2014-11-03 23:50:17

+0

@geotheory您可以使用'tags $ script(HTML())'添加javascript。查看HTML標籤和動態UI文章:http://shiny.rstudio.com/articles/。除此之外,你可能需要用一個具體的例子來提出一個新的問題。祝你好運。 – 2014-11-04 03:18:22

+0

破解它!謝謝約翰。下面的例子。 – geotheory 2014-11-04 12:25:06

3

對於其他人的利益,這是工作的公式。如果任何人都可以提出更優雅的解決方案,我會很感激。打開瀏覽器的JavaScript控制檯日誌查看對象 '數據' 正在更新..

server.R

library(shiny) 
iris <- datasets::iris 
names(iris) <- gsub('[/.]','_',tolower(names(iris))) 

shinyServer(
    function(input, output) { 
    output$json <- reactive({ 
     paste('<script>data=', 
      RJSONIO::toJSON(iris[iris$species == input$species,], byrow=T, colNames=T), 
      ';console.log(data[0]);', # print 1 data line to console 
      '</script>') 
    }) 
    } 
) 

ui.R

require(shiny) 
iris <- datasets::iris 
names(iris) <- gsub('[/.]','_',tolower(names(iris))) 
specs <- as.character(unique(iris$species)) 
names(specs) <- specs 

pageWithSidebar(
    headerPanel("minimal json handling example"), 
    sidebarPanel(selectInput("species", "Species", specs)), 
    mainPanel(
    htmlOutput("json") 
) 
)