reactivity and rhandsontable - r

I have recently discovered the rhandsontable package in r and it will be very useful in some of my r shiny projects. I have slightly modified what I saw here Get selected rows of Rhandsontable as a little tester for what I will use this package for.
I want to be able to let users change values of the data frame from within r using the rhandsontable package.So here I want df[1,1] to update each time I change that value. I am just a bit confused when it comes to wrapping a reactive function around render functions especially the renderRHandsontable function. I have used reactive functions with plotting but this is a bit different.
library(shiny)
library(rhandsontable)
ui=fluidPage(
rHandsontableOutput('table'),
verbatimTextOutput('selected'),
verbatimTextOutput("tr")
)
server=function(input,output,session)({
a<-c(1,2)
b<-c(3,4)
c<-rbind(df1,df2)
df1<-data.frame(df3)
#need reactive function around the following
output$table=renderRHandsontable(
rhandsontable(df1,selectCallback = TRUE,readOnly = FALSE)
)
output$selected=renderPrint({
cat('Selected Row:',input$table_select$select$r)
cat('\nSelected Column:',input$table_select$select$c)
cat('\nSelected Cell Value:',input$table_select$data[[input$table_select$select$r]][[input$table_select$select$c]])
df1[input$table_select$select$r,input$table_select$select$c]<-input$table_select$data[[input$table_select$select$r]][[input$table_select$select$c]]
})
#need reactive function around the following
output$tr <- renderText({
df1[1,1]
})
})
# end server
shinyApp(ui = ui, server = server)
It is an interesting area that will open up a lot in my shiny apps for users to play around with.
Thanks

Your code here is not reproducible. In the beginning of your server function, you used rbind() on df1 and df2when neither of these objects exist yet. R will throw an error (and it should!)
Because of that I will have to assume that your data frame is in fact the following:
a<-c(1,2)
b<-c(3,4)
c<-rbind(a,b)
df1<-data.frame(c)
To bind the reactivity output from Rhandsontable to your textOutput, you can use the observe() function from Shiny or even better, the handy hot_to_r function from rhandsontable itself. This function converts the handsontable data to R object.
Without changing your ui function, this will be your server function:
server <- function(input,output,session)({
a<-c(1,2)
b<-c(3,4)
c<-rbind(a,b)
df1<-data.frame(c)
output$table<-renderRHandsontable(
rhandsontable(df1)
)
#use hot_to_r to glue 'transform' the rhandsontable input into an R object
output$tr <- renderText({
hot_to_r(input$table)[1,1]
})
})
Then proceed to call your Shiny app as usual: shinyApp(ui = ui, server = server) and your output$tr now reacts to any edits on your table.

Related

Assign to global shiny environment in package

I have a shiny app (bundled as part of a package) where at the beginning of the server function I create a bunch of reactive data frames that later get used in other parts of the app.
Since quite a few dataframes get created, I wanted to make a simple setup_data() function that could be called at the beginning, in order to help keep the app code tidy. However, since the dfs are created inside a function, I need to use either <<- or assign to make sure they're available in Shiny's server environment.
library(shiny)
setup_data <- function(){
reactiveDat1 <<- shiny::reactiveValues()
reactiveDat1$mydf <<- data.frame(x = 1, y = 2)
reactiveDat2 <<- shiny::reactiveValues()
reactiveDat2$mydf <<- data.frame(x = 5, y = 10)
}
ui <- fluidPage(
titlePanel(""),
sidebarLayout(
sidebarPanel(
),
mainPanel(
)
)
)
server <- function(input, output) {
setup_data()
# rest of app goes here....
}
# Run the application
shinyApp(ui = ui, server = server)
Doing it this way generates a cran NOTE of no visible binding for '<<-' assignment, and in general it is bad practise to do global assigns in a cran package.
Therefore, is there way I can create a function that does the setup like this, but in a way conducive to shiny and cran packages? Ideally I'd like to avoid returning everything in a list, and I haven't found a way to make this work in the Shiny Modules framework as there is no corresponding UI to tie these to.
Is there any other options?
You can setup the data using the global.R file. Any R objects that are created in the global.R file become available to the app.R file, or the ui.R and server.R files respectively. Take a look at how to modularize shiny apps.
EDIT: As pointed out in the comments, you can use local = TRUE to only load objects into the shiny environment.

ShinyApp reactive error while trying to select variables from imported data set

I am very new to Shiny and R in general and I am building an app that allows users to import data, select their variables, number of trees.. ect and then run that through a random forest script and have it display the outputs. Right now I am just working on the inputs, however, I am running into a problem. The user can import a CSV but then they cannot select their variables (headers from csv). I am trying to make it reactive so the user first must import their csv before the option of selecting their variables pops up (seems simple).
Here is my code right now:
ui.R
server.R
Error in Console
I am probably just making a silly mistake because I am unfamiliar with Shiny but your help would be much appreciated.
A little background info
First off, I recommend you read this through to get a good understanding of reactivity in Shiny: Shiny Reactivity Overview. This helps a lot with variable scoping in a Shiny context too: Scoping Rules in Shiny Apps.
The issue
I believe this issue is due to you defining the variable file_to_read within the scope of shiny output: output$input_file in your server.R file. When the function read.table() looks for the variable file_to_read, it doesn't exist since it is only defined within the scope of the shiny output.
Try making a reactive value and then assigning the input$file value to it once it is uploaded by the user. You'll also have to convert your dat1 variable to a shiny reactive since you can only read reactive values in the context of other reactive sources (e.g. observe(), reactive(), observeEvent(), etc.)
file_to_read <- reactiveVal(NULL) # Set the value to NULL to initialize
output$input_file <- renderTable({
if (is.null(input$file)) return () # Check there is an input file
file_to_read(input$file) # Set the reactiveVal to the input file
})
# Make dat1 a reactive so it can be read within a shiny reactive
dat1 <- reactive({
if(is.null(file_to_read()) return (NULL) # Check for input file in reactiveVal
read.table(file_to_read()$datapath, sep = input$sep, header = input$header)
})
# Make an eventReactive to capture when there is read.table() data from dat1
reactive1 <- eventReactive(dat1, {
if (is.null(dat1)) return ()
D <- colnames(dat1)
return (list(D, D[1]))
})
I didn't test this code since you posted your data in image format and I don't have an input file, but hope this helps your error.

How to make changes reflect in many places when input is changed without ObserveEvent() in shiny

I have an input variable input$shop_id. Which is used to get data in server function using:
observeEvent(input$shop_id,{id<<-input$shop_id})
`Data=dbGetQuery(connection_name,paste0("SELECT * FROM tab_name WHERE id_shop=",id"))`
That Data is further used to create dynamic UI using selectInput()
output$dependant=renderUI({
selectInput("choice","Choose the Data you want to view",names(Data))
})
I can't come up with the logic of the arrangement of these functions. I cannot get it to work. I have created a sample data and similar sample code for someone to try on:
library(shiny)
library(ggplot2)
ui=fluidPage(
column(6,uiOutput("shop_select")),
column(6,uiOutput("cust_select")),
column(6,uiOutput("select3")),
column(12,offset=6,uiOutput("plot"))
)
server = function(input, output) {
#sample data
shopdata=data.frame(id=c(1,2,3,4,5,6,7,8,9,10),name=c("a","b","c","d","e","f","g","h","i","j"))
cdata=data.frame(id=c(123,465,6798,346,12341,45764,2358,67,457,5687,4562,23,12124,3453,12112),
name=c("sadf","porhg","wetgfjg","hwfhjh","yuigkug","syuif","rtyg","dygfjg","rturjh","kuser","zzsdfadf","jgjwer","jywe","jwehfhjh","kuwerg"),
shop=c(1,2,1,2,4,6,2,8,9,10,3,1,2,5,7),
bill_total=c(12341,123443,456433,234522,45645,23445,3456246,23522,22345,23345,23454,345734,23242,232456,345456),
crating=c(4,4.3,5,1.2,3.2,4,3.3,2.4,3.8,3,3.2,3.3,1.4,2.8,4.1))
output$shop_select=renderUI({
selectInput("shop_id","Shop ID",shopdata$id)
})
output$cust_select=renderUI({
selectInput("cust_id","Customer ID",cdata$id,multiple = T)
})
output$select3=renderUI({
a=input$shop_id
selectInput("choice","Choose the Data you want to view",names(cdata))
})
output$plot=renderUI({
renderPlot({
require(input$choice)
plotOutput(
ggplot(cdata,aes(x=cust_id,y=input$choice))
)})})
}
shinyApp(ui=ui,server=server)
I know I am not clear on the question. Fixing the code which I posted is more than enough to clear my doubt. Basically, I just need to know what is the logic when we have to use while using a renderUI() which is dependent on another renderUI()
If you want to set up a series of subsetting operations and then call renderUI()s on each subset, you will need to take advantage of Shiny's reactive({}) expressions.
Reactive expressions are code chunks that produce variables and their magic is that they "watch" for any changes to their input data. So in your case one you select a shop_id in the first UI element, the reactive expression detects that and updates itself, automatically!
Here is an example showing the updating, just select different shop_id's and watch the available cust_ids change on the fly.
library(shiny)
library(ggplot2)
library(tidyverse)
ui=fluidPage(
column(6,uiOutput("shop_select")),
column(6,uiOutput("cust_select")),
column(6,uiOutput("select3")),
column(12,offset=6,tableOutput("plot"))
)
server = function(input, output) {
#sample data
shopdata=data.frame(id=c(1,2,3,4,5,6,7,8,9,10),name=c("a","b","c","d","e","f","g","h","i","j"))
cdata=data.frame(id=c(123,465,6798,346,12341,45764,2358,67,457,5687,4562,23,12124,3453,12112),
name=c("sadf","porhg","wetgfjg","hwfhjh","yuigkug","syuif","rtyg","dygfjg","rturjh","kuser","zzsdfadf","jgjwer","jywe","jwehfhjh","kuwerg"),
shop=c(1,2,1,2,4,6,2,8,9,10,3,1,2,5,7),
bill_total=c(12341,123443,456433,234522,45645,23445,3456246,23522,22345,23345,23454,345734,23242,232456,345456),
crating=c(4,4.3,5,1.2,3.2,4,3.3,2.4,3.8,3,3.2,3.3,1.4,2.8,4.1))
output$shop_select=renderUI({
selectInput("shop_id","Shop ID",shopdata$id)
})
cdata_reactive <- reactive({
req(input$shop_id)
filter(cdata, shop == input$shop_id)
})
output$cust_select=renderUI({
selectInput("cust_id","Customer ID",cdata_reactive()$id, multiple = T)
})
output$select3=renderUI({
selectInput("choice","Choose the Data you want to view",names(cdata_reactive()))
})
output$plot <- renderTable({
filter(cdata_reactive(), id %in% input$cust_id) %>%
.[input$choice]
})
}
shinyApp(ui=ui,server=server)
A renderUI generates UI elements. Therefore it can only contain ui functions. You need to use it to generate the plotOutput and then use renderPlot separately to add content.
The names you assign in the aes call are the names of variables in the data frame you provided. Therefore x should be id not the values of input$cust_id (which must be called as input$cust_id, since it refers to an input object.
input$choice returns a string, not an object, so you can't use it normally in aes (recall that if this was a normal dataframe your aes would be aes(x=id, y=choice) not aes(x='id', y='choice'). Therefore, you need to use aes_ with the as.name function to convert those strings into proper variable names.
What I think you want to do with input$cust_id is filter cdata to only include rows with the chosen id values. dplyr::filter is the best way to do that.
Finally, you're missing a geom_* in your ggplot call which is needed to actually render your data.
If you replace your output$plot <- ... call with the below code it should work the way I think you want it to:
output$plot=renderUI({
plotOutput('plotout')
})
output$plotout <- renderPlot({
ggplot(dplyr::filter(cdata, id %in% input$cust_id),
aes_(x=as.name('id'),y=as.name(input$choice))) +
geom_point()
})
As for the question in your title, you only need to use observeEvent if you want to limit the code in the expression to only run when a specific trigger occurs. Any reactive expression (reactive, observe, render_ etc.) will become invalidated and update itself if any reactive value (either a reactiveValues object or an input$...) changes. If you have an input$ or a reactive value in a render_ block, it will update if they change -- no observeEvent needed.

Shiny print reactive df to console (glimpse(myreactive_df) for debugging purposes?

I'm trying to debug my Shiny app and would like to view a reactive dataframe with e.g. glimpse(df).
Initially I tried to create a breakpoint and then view the environment by my reactive df is a value not an object when used inside server.r. I also tried browser() but was not sure what it would do.
I did some searching on SO and tried various things using sink(), renderPrint() but had no success.
How can I print the contents of glimpse(some_reactive_df()) to the console when I run my app?
Calling print() from within the reactive({}) expression will do that.
library(shiny)
library(dplyr)
shinyApp(
ui <- fluidPage(
selectizeInput("cyl_select", "Choose ya mtcars$cyl ", choices = unique(mtcars$cyl)),
tableOutput("checker") # a needed output in ui.R, doesn't have to be table
),
server <- function(input, output) {
d <- reactive({
d <- dplyr::filter(mtcars, cyl %in% input$cyl_select)
print(glimpse(d)) # print from within
return(d)
})
output$checker <- renderTable({
glimpse(d()) # something that relies on the reactive, same thing here for simplicty
})
})
Assuming you provide Shiny a reason to run (and re-run) your reactive of interest, by having it be involved with a rendering in server() and linked output in ui(). This is usually the case for my debugging scenarios but it won't work unless the reactive is being used elsewhere in app.R.

Shiny app not updating the data

I have a shiny page looking like that:
library(all my required packages)
source("that file that contains a function to grab my data")
data <- function_from_sourced_file()
server <- function(input, output)
ui <- shinyUI()
shinyApp(ui = ui, server = server)
Now this works fine but I need the shiny app to reflect the changes on said data and to do so I have to either rerun the runApp() function or :w the app.R file in vim. Is it possible to ask the shiny server to rerun the entire file each it is accessed?
thanks
One of the quick ways to do so is using reactivePoll.
reactivePoll
Value
A reactive expression that returns the result of valueFunc, and invalidates when checkFunc changes.
Description
Used to create a reactive data source, which works by periodically polling a non-reactive data source.
Example
reactivePoll and reactiveFileReader

Resources