Error in grobToDev.default(gTree, dev) - rstudio-server

I am trying to build a app with shiny+gridSVG. This problem happened constantly and I have no idea about it.
My server.R:
library(grid)
library(lattice)
library(gridSVG)
shinyServer(function(input, output) {
data = reactive({
inFile = input$file1
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath, header=input$header,
sep=input$sep, quote=input$quote)
})
featurelist = reactive({
return (colnames(data()))
})
output$classUI = renderUI({
selectInput("classlabel","Classify by:", featurelist())
})
output$svg.grid = reactive({
dat = data()
features = featurelist()
#group = dat[,c(which(features == input$classlabel))]
subsetted.features = features[-c(which(features == input$classlabel))]
#classlabel.level = levels(group)
xyplot.out = xyplot(subsetted.features[1] ~ subsetted.features[2]|input$classlabel,
data = dat
)
tempsvg <- tempfile(fileext=".svg")
on.exit(unlink(tempsvg))
gridToSVG(name=tempsvg)
svgoutput <- readLines(tempsvg, n=-1)
svgoutput
})
})
this is my js:
<script>
var networkOutputBinding = new Shiny.OutputBinding();
$.extend(networkOutputBinding, {
find: function(scope) {
return $(scope).find('.shiny-network-output');
},
renderValue: function(el, data) {
$(el).html(data.join(''));
}
});
Shiny.outputBindings.register(networkOutputBinding, 'timelyportfolio.networkbinding');
</script>
And the error message in the console is:
Error in grobToDev.default(gTree, dev) : We shouldn't be here!
Do any one know the reason?

I can't help with the reason why, but I had the same Error message and solved it by doing the following:
Quitting RStudio.
Updating to the latest version of R (in my case this was 3.2)
Re-starting RStudio
Re-installing the gridSVG package
The problem went away.
BTW: here is a neat way of re-installing your packages: http://www.r-bloggers.com/automated-re-install-of-packages-for-r-3-0/

I'm hitting this problem too (not with shiny; I'm just trying to export a plot to SVG), and I'm not sure why—but for me it only happens when I call grid.export within my script. If I re-display my plot and call it again interactively, it runs fine. I guess there's some sort of environmental difference playing into it?

Related

check existence of reactive in shiny

I have a shiny app where you can upload some raw data and build a summarizedExperiment (let's call it RAW) or you can upload an already processed summarizedExperiment (let's call it FINAL). Now I need to save in a reactive object RAW or FINAL. I tried something like this:
sumexp_all = reactive({
if(!is.null(RAW())){
list(sumexp_data = RAW()$sumexp_data, sumexp_data_mean = RAW()$sumexp_data_mean, replicates = RAW()$replicates)
}else if(!is.null(input$finalsumexpinput)){
readRDS(file = input$finalsumexpinput$datapath)
}else{
NULL
}
})
But in this case it works only if I have RAW (if I don't have RAW (so should be NULL since there are many req() in the pipeline) and I want to upload FINAL, nothing happens). If reverse the if conditions (before FINAL and then RAW) I can upload the FINAL. What's wrong? Is it correct to evaluate a reactive with is.null()?
I tried something else like this:
sumexp_all = reactive({
checkerror <- tryCatch(RAW(), error = function(e) "empty")
if(checkerror != "empty"){
list(sumexp_data = RAW()$sumexp_data, sumexp_data_mean = RAW()$sumexp_data_mean, replicates = RAW()$replicates)
}else if(!is.null(input$finalsumexpinput)){
readRDS(file = input$finalsumexpinput$datapath)
}else{
NULL
}
})
But the shiny app crashes and returns this error:
Warning: Error in if: argument is of length zero
And that's weird because if I print checkerror it correctly returns "empty" if's empty.
UPDATE:
I made some testing in order to find where is the problem, and the problem is with the RAW() reactive. Basically I tried this code to find the problem:
checkraw = reactive({
if(is.null(RAW())){
"raw is null"
}else{
"raw is not null"
}
})
checkinp = reactive({
if(is.null(input$finalsumexpinput$datapath)){
"input non loaded"
}else{
"input loaded"
}
})
output$printcheck= renderPrint({
paste(checkraw(), ",", checkinp())
})
So what I expect from this code is that if RAW() doesn't exist and I uplaod the rds file, it' printed "raw is null, input loaded", but what happens is that nothing is displayed.
If RAW() exists then it's correctly printed "raw is not null, input not loaded"
Then I tried to print only checkinp() (removing the checkraw() reactive) and then checkinp() is correctly printed.
So it seems to me that the problem is in the evaluation of the RAW() reactive. Do you think that the problem could be that RAW() depends on others reactive variables (so there is a req() inside it).
EDIT:
Here is a reproducible example.
ui <- shinyUI(pageWithSidebar(
headerPanel("check"),
sidebarPanel(
actionButton("Button", "enable raw"),
textInput("text", "write something", "something..."),
br(),
),
mainPanel(
verbatimTextOutput("printcheck"),
verbatimTextOutput("checkfin")
)
))
server <- shinyServer(function(input, output) {
stepa = eventReactive(input$Button, {
rnorm(100)
})
stepb = reactive({
req(stepa())
stepa() * 100
})
output$printcheck = renderPrint({
is.null(stepb())
})
fin = reactive({
if(!is.null(stepb())){
stepb()
}else{input$text}
})
output$checkfin = renderPrint({
fin()
})
})
shinyApp(ui=ui,server=server)
As you can see output$checkfin is printed ONLY if stepb() is not null even if in this case should be printed input$text
I posted the problem on the shiny github page. For those interested, here's the answer.
https://github.com/rstudio/shiny/issues/3533

Read json file continuously

I want to read a json file continuously, e.g. every 1000 ms.
One option my be reactiveFileReader
reactiveFileReader(intervalMillis, session, filePath, readFunc, ...)
described here.
This function seems only working with csv files and not for json files:
file_data <- reactiveFileReader(intervalMillis = 1000, NULL, filePath = json_path, readFunc = read.json)
observe({
View(file_data())
})
Error in View : object read.json not found
With reactivePoll like here:
getJsonData <- reactivePoll(1000, session,
checkFunc = function() {
if (file.exists(path))
file.info(path)$mtime[1]
else
""
},
valueFunc = function() {
read_json(path)
}
I get nearly what I want, but this function is not working in my context. How do I force the program to read the file every second and not only when the content of the file is changing?
Are there other possibilities I not have thought about yet?
In your first way, you wrote read.json instead of read_json.
With your second way, you could replace file.info(path)$mtime[1] with runif(1, 0, 1e6). You would be very unlucky if runif returns the same number two consecutive times.
Finally, a third way could be:
server <- function(input, output, session){
autoInvalidate <- reactiveTimer(1000)
getJsonData <- reactive({
autoInvalidate()
read_json("path/to/file.json")
})
}
Here is a reprex on how to use reactiveFileReader with a json file.
I used a future to detach the writing process from the shiny session - you can simply replace this with your json input.
library(shiny)
library(jsonlite)
library(datasets)
library(promises)
library(future)
plan(multisession(workers = 2))
ui <- fluidPage(
uiOutput("printResult")
)
server <- function(input, output, session) {
json_path <- tempfile(fileext = ".json")
write_json(NULL, json_path)
# async file writing process
future({
for(i in seq_len(nrow(iris))){
Sys.sleep(1)
write_json(iris[i,], json_path)
}
})
file_data <- reactiveFileReader(intervalMillis = 1000, NULL, filePath = json_path, readFunc = read_json)
output$printResult <- renderUI({
req(file_data())
})
}
shinyApp(ui, server)

failed to display variable data types in shiny flexdashboard

I am trying to display variable types dynamically and my code is something like this (using into flexdashboard shiny app):
tblCls <- reactive({
req(input$file1)
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}else{
datatable(head(read.csv(inFile$datapath, header = input$header), 5))
}
})
output$class <- renderText({
print(class( tblCls() ))
})
textOutput("class")
I read the csv file from fileInput method.
The result is expected something what we get when do str(DF) in R but what I am getting is datatables htmlwidget as output.
Not sure what I have done wrong here, need to understand the correct method.
Here's what you need -
tblCls <- reactive({
req(input$file1) # if else not needed when using req()
head(read.csv(input$file1$datapath, header = input$header), 5)
})
output$class <- renderPrint({
str(tblCls())
})
textOutput("class")

R shiny error with renderTable

I am building a shiny app for doing some network analyses. I want to calculate properties for the network using a function that is stored in global.R. However, I am not able to get the table output.
Here is the the part of my ui.R where I set the output for the table
# More ui.R above
mainPanel(
tabsetPanel(id = "conditionedPanels",
tabPanel("Network Properties",br(),value = 1,
actionButton('netproperty', label='Calculate Properties',class="btn btn-primary"),
h3(textOutput("Data Summary", container = span)),
tableOutput('prop_table')),
##... More ui.R code below
and here is my server.R:
shinyServer( function(input, output, session) {
## Get the properties
props <- reactive({
if (input$netproperty <= 0){
return(NULL)
}
result <- isolate({
input$netproperty
tryCatch ({
if(input$data_input_type=="example"){
if(input$datasets == "Network1"){
load("data/Network1.rda")
props <- graph_topology(g)
props
} else if (input$datasets == "Network2"){
load("data/Network1.rda")
props <- graph_topology(g)
props
} else if (input$datasets == "Network3"){
el <- read.delim("data/Network3.txt")
g <- graph.data.frame(el, directed = FALSE)
props <- graph_topology(g)
props
} else if (input$datasets == "Network4") {
el <- read.delim("data/Network4.txt")
g <- graph.data.frame(el, directed = FALSE)
props <- graph_topology(g)
props
}
} else if (input$data_input_type=="custom"){
if (is.null(input$dt_file))
return(NULL)
inFile <- input$dt_file
dataDT <- as.matrix(read.delim(inFile$datapah, sep="\t", header = FALSE, fill = TRUE))
g <- graph.data.frame(dataDT, directed = FALSE)
props <- graph_topology(g)
props
}
},
error = function(err) {
print(paste("Select Example or custom data set"))
})
})
result
})
## Output properties table
output$prop_table <- renderTable({
props()
})
}
When I press the button calculate properties, I get the error message always, telling me that I need to select example or custom data. I have tried with custom and example datasets, and the error remains. If I remove the tryCatch command in server.R I get the error of length equal zero. It seems that the function graph_topology in my global.R files is not working properly, but if I run it outside of the shiny app I get a matrix, that I thought it could be easily visualize with renderTable. I have also tried instead of using uiOutput in the ui.R using tableOutput but I have the same problem.

DownloadHandler function in R package shiny does not produce a csv file for downloading

In my below example of a simple shiny app i recently created, im currently trying to include also the possibility of downloading a data frame that is created from the results. I mention here part of the server.R script in order to not make a huge post:
shinyServer(function(input, output) {
table_options<- list(lengthMenu = list(c(5,10,15,20),
c('5','10', '15', '20')), pageLength = 15, ordering=TRUE,
class = 'cell-border stripe',dom ='t',scrollX = TRUE,
fixedColumns = list(leftColumns = 2, rightColumns = 1))
inTable <- reactive({# upload a tsv file
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.table(inFile$datapath,header=input$header,
sep="\t",stringsAsFactors = FALSE)
}) #END REACTIVE
rv <- reactiveValues()
rv$data <- NULL # to further use it into the observeEvent below
observeEvent(input$goButton, {
df <- inTable()
# some data manipulation with df...
if(input$repo_option=="mimic"){
# some functions here that result to a data frame named final dat
rv$data <- final.dat
rv$data
}
else if(input$repo_option=="reverse"){
# similar procedure...
rv$data <- final.dat
rv$data
}
})
output$contents <- DT::renderDataTable({
expr=DT::datatable(rv$data, options=table_options,
extensions ='FixedColumns',selection="none")
})
output$downloadData <- downloadHandler(
filename = function() { paste("input$file1", ".csv", sep=",") },
content = function(file) {
write.csv(rv$data,file)
}
)
})
My main issue is that, although the output$contents works fine in the app, when i press the download button from the ui.R server (not posted here for simplicity), the download "pop-up" window appears, but the saving does not work. Thus, i suspect that is something wrong with the code in the downloadHandler function, but any ideas or help ?

Resources