Reading objects from shiny output object not allowed?
The issue is that the output object is generating all of the web display stuff as well. Instead, you need to pull the data separately for the download. You could do it with a second call to brushedPoints
in the download code. Better, however, is to use a reactive()
function to do it just once, then call that everywhere that you need it. Here is how I would modify your code to make that work:
data(iris)
ui <- basicPage(
plotOutput("plot1", brush = "plot_brush"),
verbatimTextOutput("info"),mainPanel(downloadButton('downloadData', 'Download'))
)
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(iris,aes(x=Sepal.Width,y=Sepal.Length)) + geom_point(aes(color=factor(Species))) + theme_bw()
})
selectedData <- reactive({
brushedPoints(iris, input$plot_brush)
})
output$info <- renderPrint({
selectedData()
})
output$downloadData <- downloadHandler(
filename = function() {
paste('SelectedRows', '.csv', sep='') },
content = function(file) {
write.csv(selectedData(), file)
}
)
}
shinyApp(ui, server)
(Note, with ggplot2
, you do not need to explicitly set xvar
and yvar
in brushedPoints
. So, I removed it here to increase the flexibility of the code.)
I am not aware of any "lasso" style free drawing ability in shiny
(though, give it a week -- they are constantly adding fun tools). However, you can mimic the behavior by allowing user to select multiple regions and/or to click on individual points. The server logic gets a lot messier, as you need to store the results in a reactiveValues
object to be able to use it repeatedly. I have done something similar to allow me to select points on one plot and highlight/remove them on other plots. That is more complicated than what you need here, but the below should work. You may want to add other buttons/logic (e.g., to "reset" the selections), but I believe that this should work. I did add a display of the selection to the plot to allow you to keep track of what has been selected.
data(iris)
ui <- basicPage(
plotOutput("plot1", brush = "plot_brush", click = "plot_click")
, actionButton("toggle", "Toggle Seletion")
, verbatimTextOutput("info")
, mainPanel(downloadButton('downloadData', 'Download'))
)
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(withSelected()
, aes(x=Sepal.Width
, y=Sepal.Length
, color=factor(Species)
, shape = Selected)) +
geom_point() +
scale_shape_manual(
values = c("FALSE" = 19
, "TRUE" = 4)
, labels = c("No", "Yes")
, name = "Is Selected?"
) +
theme_bw()
})
# Make a reactive value -- you can set these within other functions
vals <- reactiveValues(
isClicked = rep(FALSE, nrow(iris))
)
# Add a column to the data to ease plotting
# This is really only necessary if you want to show the selected points on the plot
withSelected <- reactive({
data.frame(iris
, Selected = vals$isClicked)
})
# Watch for clicks
observeEvent(input$plot_click, {
res <- nearPoints(withSelected()
, input$plot_click
, allRows = TRUE)
vals$isClicked <-
xor(vals$isClicked
, res$selected_)
})
# Watch for toggle button clicks
observeEvent(input$toggle, {
res <- brushedPoints(withSelected()
, input$plot_brush
, allRows = TRUE)
vals$isClicked <-
xor(vals$isClicked
, res$selected_)
})
# pull the data selection here
selectedData <- reactive({
iris[vals$isClicked, ]
})
output$info <- renderPrint({
selectedData()
})
output$downloadData <- downloadHandler(
filename = function() {
paste('SelectedRows', '.csv', sep='') },
content = function(file) {
write.csv(selectedData(), file)
}
)
}
shinyApp(ui, server)
getting error: Reading objects from shinyoutput object not allowed - multiple linear regression model
Without having some data at hand to reproduce your app its hard to spot the error and makes it more of a guessing game.
So my first guess would be, that you're not handling the reactivity in your app correctly. You're render* functions are calling reactive values, but when no file was uploaded and no Regressor was chosen, there is no data to work with, so it will throw an error. I would suggest checking out the Shiny principles of reactivity and the functions observeEvent, req, validate
.
Then you can remove the lines with is.null(*)
, as the req()
function does that for you.
Next thought, what is mpg
?
And I think you should change summary(modelq())
to summary(modelq)
too, as you just want to print the summary of the object and not call the object.
Calling library(shiny)
once is enough. ;)
In the prediction you are also calling df
, which is not assigned in that function. I added a reactiveValues
object, where you can save other objects in a reactive way. And in your second renderUI we add the data to the reactiveValues object like thisdf$file <- df
. And in the prediction function you can call the data like this predict(modelq,df$file)
.
I also changed the regformula
to an eventReactive() which will be executed every time you press the action button.
And lastly, I changed to formula creation to as.formula(paste("mpg",'~',paste(input$independents, collapse= "+")))
, as if you only call input$independents, it will only take the first argument.
library(shiny)
library(datasets)
library(caret)
library(curl)
ui <- fluidPage(
titlePanel("My first predictive model"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$hr(),
verbatimTextOutput("smp"),
uiOutput("dependent"),
uiOutput("independents"),
tags$hr(),
actionButton("action", "Predict!")
),
mainPanel(
verbatimTextOutput("summary1")
)
)
)
server <- function(input, output, session) {
filedata <- reactive({
infile <- input$file1
read.csv(infile$datapath)
})
df <- reactiveValues(file = NULL)
output$dependent <- renderUI({
req(input$file1)
df <- filedata()
items=names(df)
names(items)=items
selectInput("dependent","Select ONE variable as dependent variable from:",items)
})
output$independents <- renderUI({
req(input$file1)
df <- filedata()
df$file <- df
checkboxGroupInput('independents','Select the regressors', choices = names(df))
})
#regression formula
regformula <- eventReactive(input$action, {
as.formula(paste("mpg",'~',paste(input$independents, collapse= "+")))
})
#model
output$summary1 <- renderPrint({
req(regformula())
req(input$file1)
modelq <- lm(regformula(),data=mtcars)
df <- filedata()
pred1<-predict(modelq,df);
names <- df$X
data.frame(X = as.character(names), Prediction = pred1)
})
}
shinyApp(ui, server)
R Shiny: Error in $.shinyoutput: Reading from shinyoutput object is not allowed.
Found the solution: I just need to replace output$paste0("data", i)
by output[[paste0("data", i)]]
.
Hope this will help somebody
Reading objects from shinyoutput object are not allowed
You are only missing a '-' at the end of your server.R file. If you look closely at your output$gvis you will notice that you are not assigning output$gvis but actually comparing it to your rendered Gvis object with the <
operator (which is why you get the error about reading objects from output). Just change the output$gvis < renderGvis({...
to output$gvis <- renderGvis({...
and everything should work fine.
Issues about this error: Error in $.shinyoutput: Reading from shinyoutput object is not allowed.
I cannot test it because your code sample is not reproducible. But what the error states is that you are trying to access an UI output variable directly in your server. Of course you can access the generated output
in your server, but then it becomes an input
, right?
This happens when you are checking if output$nivel
is either 1 or 2. You should access the nivel
variable with input$nivel
in your server.
Related Topics
Building a List in a Loop in R - Getting Item Names Correct
Use Dplyr's Summarise_Each to Return One Row Per Function
Creating a Pareto Chart with Ggplot2 and R
How to Change the Background Color of the Shiny Dashboard Body
Manipulating Multiple Files in R
How to Split the Main Title of a Plot in 2 or More Lines
How to Replicate a Ddply Behavior That Uses a Custom Function with Dplyr
Reading in Chunks at a Time Using Fread in Package Data.Table
Rmarkdown Directing Output File into a Directory
R Package Xtable, How to Create a Latextable with Multiple Rows and Columns from R
How to Plot a Subset of a Data Frame in R
How to Check If a Sequence of Numbers Is Monotonically Increasing (Or Decreasing)
How to Tell What Packages You Have Used in R
Formatting Ggplot2 Axis Labels with Commas (And K? Mm) If I Already Have a Y-Scale
Using R and Plot.Ly - How to Script Saving My Output as a Webpage
How to Prevent Exposure of My Password When Using Rgoogledocs
Compute Rolling Sum by Id Variables, with Missing Timepoints