R - Difference between calling value vs value() - r

Why should you call df() instead of df in the code below? Is this the correct syntax to use with the reactive function?
function(input, output, session){
df <- reactive({
head(cars, input$nrows)
})
output$plot <- renderPlot({
plot(df()) #Why call df() instead of df?
})
output$table <- renderTable({
df() #Why call df() instead of df?
})
}

You've set the value of df to equal the return value from a call to reactive.
From ?reactive:
Value
a function, wrapped in a S3 class "reactive"
df, therefore, is a function which, when called, will evaluate the saved expression and return the current value (and also trigger updates reactively).

Related

Shiny manipulating input$df with reactive

I am new to shiny and trying to modify this code to allow for the function to be used from a dynamically selected csv.
## function to return random row number from data set
getTweet <- function(){
tweetData[sample(nrow(tweetData), 1), ]
}
our_tweet <- isolate(appVals$tweet)
output$tweet <- renderText({ our_tweet$tweet })
output$screen_name <- renderText({ our_quote$screen_name })
output$resultsTable <- renderDataTable({appVals$ratings})
The above code works when tweetData is a static csv read in through read.csv() but when I try to use a drop down to select csv the only way I am able to run without error is putting it inside of a renderDataTable() function. How could I use reactive values within input$file and still be able to run the above code.
Code using renderDataTable():
output$test <- renderDataTable({
req(input$file)
csvName <- paste0('../path/to/file/', input$file)
selectedData <- read.csv(csvName)
selectedData
})
I want to be able to do something like this:
csvName <- paste0('../path/to/file/', input$file)
selectedData <- read.csv(csvName)
selectedData[sample(nrow(selectedData), 1), ]
You could create reactive functions:
csvName <- reactive(paste0('../path/to/file/', input$file))
selectedData <- reactive(read.csv(csvName()))
You can then use the reactive functions in other reactives like renderDataTable:
output$test <- renderDataTable({
selectedData()[sample(nrow(selectedData()), 1), ]
})
Don't forget the () when calling the result of reactive functions : csvName(), selectedData(), , ...

Error in .getReactiveEnvironment()$currentContext() while using reactive output in reactiveValues function

I'm trying to get a reactiveValue that is depending on a reactive. In the real code (this is a very simplified version), I load a dataset interactively. It changes when pushing the buttons (prevBtn/nextBtn). I need to know the number of rows in the dataset, using this to plot the datapoints with different colors.
The question: Why can't I use the reactive ro() in the reactiveValues function?
For understanding: Why is the error saying "You tried to do something that can only be done from inside a reactive expression or observer.", although ro() is used inside a reactive context.
The error is definitely due to vals(), I already checked the rest.
The code :
library(shiny)
datasets <- list(mtcars, iris, PlantGrowth)
ui <- fluidPage(
mainPanel(
titlePanel("Simplified example"),
tableOutput("cars"),
actionButton("prevBtn", icon = icon("arrow-left"), ""),
actionButton("nextBtn", icon = icon("arrow-right"), ""),
verbatimTextOutput("rows")
)
)
server <- function(input, output) {
output$cars <- renderTable({
head(dat())
})
dat <- reactive({
if (is.null(rv$nr)) {
d <- mtcars
}
else{
d <- datasets[[rv$nr]]
}
})
rv <- reactiveValues(nr = 1)
set_nr <- function(direction) {
rv$nr <- rv$nr + direction
}
observeEvent(input$nextBtn, {
set_nr(1)
})
observeEvent(input$prevBtn, {
set_nr(-1)
})
ro <- reactive({
nrow(dat())
})
output$rows <- renderPrint({
print(paste(as.character(ro()), "rows"))
})
vals <- reactiveValues(needThisForLater = 30 * ro())
}
shinyApp(ui = ui, server = server)
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.)
I think you want
vals <- reactiveValues(needThisForLater = reactive(30 * ro()))
Not everything in a reactiveValues list is assumed to be reactive. It's also a good place to store constant values. So since it's trying to evaluate the parameter you are passing at run time and you are not calling that line in a reactive environment, you get that error. So by just wrapping it in a call to reactive(), you provide a reactive environment for ro() to be called in.

Is it possible to create a user-defined function that takes reactive objects as input? How do I do it?

So, I've been on google for hours with no answer.
I want to create a user-defined function inside the server side that takes inputs that I already know to wrap reactive({input$feature)} but the issue is how to incorporate reactive values as inputs too.
The reason why I want to do this is because I have a navbarPage with multiple tabs that shares elements such as same plots. So I want a user defined function that creates all the similar filtering and not have to create multiple of the same reactive expression with different input and reactive variable names which take up 2000+ lines of code.
server <- function(input, output) {
filtered_JointKSA <- reactiveVal(0)
create_filtered_data <- function(df, input_specialtya, filtered_JointKSA) {
if (input_specialtya == 'manual') {
data <- filter(data, SPECIALTY %in% input_specialtyb)
}
if (filtered_JointKSA != 0) {
data <- filter(data, SPECIALTY %in% filtered_JointKSA)
}
reactive({return(data)})
}
filtered_data <- create_filtered_data(df,
reactive({input$specialty1}),
filtered_JointKSA())
observeEvent(
eventExpr = input$clickJointKSA,
handlerExpr = {
A <- filtered_JointKSA(levels(fct_drop(filtered_data()$`Joint KSA Grouping`))[round(input$clickJointKSA$y)])
A
}
)
This gets me an error:
"Error in match(x, table, nomatch = 0L) :
'match' requires vector arguments"
The error is gone if I comment out where I try to create filtered_data but none of my plots are created because filtered_data() is not found.
What is the correct approach for this?
Ideally, I would like my observeEvents to be inside user defined functions as well if that has a different method.
This example may provide some help, but it's hard to tell without a working example. The change is to wrap the call to your function in reactive({}) rather than the inputs to that function, so that the inputs are all responsive to user input and the function will update.
library(shiny)
ui <- fluidPage(
numericInput("num", "Number", value = NULL),
verbatimTextOutput("out")
)
server <- function(input, output){
## User-defined function, taking a reactive input
rvals <- function(x){
req(input$num)
if(x > 5){x * 10} else {x*1}
}
# Call to the function, wrapped in a reactive
n <- reactive({ rvals(input$num) })
# Using output of the function, which is reactive and needs to be resolved with '()'
output$out <- renderText({ n() })
}
shinyApp(ui, server)

Capturing instance of reactive values?

In R Shiny, Is there a way of capturing a particular instance of reactive value so then that instance is totally unreactive?
So I'd have a table made up of reactive values and when the user hits the submit button those values are copied over to an un reactive table which I can then go on to manipulate etc.
So in the following code, the user enters their values into a table from rhandsontable package (which is awesome btw), and all I am trying to do is convert it to a basic data frame namely tabplot which should be unreactive so I can go ahead and do any type of operations on it.
library(shiny)
library(rhandsontable)
seq1 <- seq(1:6)
mat1 <- matrix(seq1, 2)
tabplot<-data.frame(car=numeric(2),num=numeric(2),truck=numeric(2))
did_recalc <- FALSE
ui <- fluidPage(
rHandsontableOutput('table'),
tableOutput('result'),
tableOutput('kl'),
textOutput('ca'),
actionButton("goButton","Confirm"),
actionButton("checkButton","Apply"),
br(),
actionButton("recalc", "Return to original values")
)
server <- function(input,output,session)({
tabplot<-data.frame(car=numeric(2),num=numeric(2),truck=numeric(2))
seq1 <- seq(1:6)
mat1 <- matrix(seq1, 2)
mat1<-data.frame(mat1)
#creates reactive values for the data frame
#obviously they have to be reactive values to function with the rhandsontable which is being continuously updated
#as the documentation says "values taken from the reactiveValues object are reactive but the object itself is not
values <- reactiveValues(data=mat1)
#if recalc --- which connects to an action button in the ui is hit, values goes back to original data frame
observe({
input$recalc
values$data<-mat1
})
#Where the magic happens
output$table <- renderRHandsontable({
rhandsontable(values$data,selectCallback = TRUE)
})
#this changes the handsontable format to an r object
observe({
if(!is.null(input$table))
values$data <-hot_to_r(input$table)
})
#Here we create a reactive function that creates a data frame of the rhandsontable output but it is a reactive function
fn<-reactive({
co<-data.frame((values$data))
return(co)
})
#Bit of testing, this demonstrates that the fn() is only updated after the button is pressed
output$result<-renderTable({
input$goButton
isolate({
fn()
})
})
isolate({
# tabplot<-reactive({ #Format co[desired row:length(colums)][desired column]
tabplot[1,1:3][1]<-fn()[1,1:3][1]
tabplot[1,1:3][2]<-fn()[1,1:3][2]
tabplot[1,1:3][3]<-fn()[1,1:3][3]
tabplot[2,1:3][1]<-fn()[2,1:3][1]
tabplot[2,1:3][2]<-fn()[2,1:3][2]
tabplot[2,1:3][3]<-fn()[2,1:3][3]
})
output$kl<-renderTable({
tabplot
})
observe({
input$goButton
output$ca<-renderText({
tabplot$car
cat('\nAccessing Subset with $:', tabplot$car)
cat('\nAccessing specific cell:',tabplot[1,3])
cat('\noperations on specific cell:',tabplot[1,3]*2)
})
})
})
shinyApp(ui = ui, server = server)
This might be what you want. It leverages the much scorned <<- operator, but it is what I do when I need to subvert the "lazy reactive" architecture of shiny.
Note I set a parallel dataframe tabplot1 and display it beneath where you display tabplot.
library(shiny)
library(rhandsontable)
seq1 <- seq(1:6)
mat1 <- matrix(seq1, 2)
tabplot<-data.frame(car=numeric(2),num=numeric(2),truck=numeric(2))
did_recalc <- FALSE
ui <- fluidPage(
rHandsontableOutput('table'),
tableOutput('result'),
tableOutput('kl'),
tableOutput('kl1'),
textOutput('ca'),
actionButton("goButton","Confirm"),
actionButton("checkButton","Apply"),
br(),
actionButton("recalc", "Return to original values")
)
server <- function(input,output,session)({
tabplot<-data.frame(car=numeric(2),num=numeric(2),truck=numeric(2))
tabplot1 <- tabplot
seq1 <- seq(1:6)
mat1 <- matrix(seq1, 2)
mat1<-data.frame(mat1)
#creates reactive values for the data frame
#obviously they have to be reactive values to function with the rhandsontable which is being continuously updated
#as the documentation says "values taken from the reactiveValues object are reactive but the object itself is not
values <- reactiveValues(data=mat1)
#if recalc --- which connects to an action button in the ui is hit, values goes back to original data frame
observe({
input$recalc
values$data<-mat1
})
#Where the magic happens
output$table <- renderRHandsontable({
rhandsontable(values$data,selectCallback = TRUE)
})
#this changes the handsontable format to an r object
observe({
if(!is.null(input$table))
values$data <-hot_to_r(input$table)
})
#Here we create a reactive function that creates a data frame of the rhandsontable output but it is a reactive function
fn<-reactive({
co<-data.frame((values$data))
return(co)
})
#Bit of testing, this demonstrates that the fn() is only updated after the button is pressed
output$result<-renderTable({
input$goButton
tabplot1 <<- data.frame(values$data)
colnames(tabplot1) <<- colnames(tabplot)
isolate({
fn()
})
})
isolate({
# tabplot<-reactive({ #Format co[desired row:length(colums)][desired column]
tabplot[1,1:3][1]<-fn()[1,1:3][1]
tabplot[1,1:3][2]<-fn()[1,1:3][2]
tabplot[1,1:3][3]<-fn()[1,1:3][3]
tabplot[2,1:3][1]<-fn()[2,1:3][1]
tabplot[2,1:3][2]<-fn()[2,1:3][2]
tabplot[2,1:3][3]<-fn()[2,1:3][3]
})
output$kl<-renderTable({
tabplot
})
output$kl1<-renderTable({
input$goButton
tabplot1
})
observe({
input$goButton
output$ca<-renderText({
tabplot$car
cat('\nAccessing Subset with $:', tabplot$car)
cat('\nAccessing specific cell:',tabplot[1,3])
cat('\noperations on specific cell:',tabplot[1,3]*2)
})
})
})
shinyApp(ui = ui, server = server)
Yielding:

What's the difference between Reactive Value and Reactive Expression?

In Shiny tutorial, there is an example:
fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2))
shinyServer(function(input, output) {
currentFib <- reactive({ fib(as.numeric(input$n)) })
output$nthValue <- renderText({ currentFib() })
output$nthValueInv <- renderText({ 1 / currentFib() })
})
I don't get how reactive caches the values. Does it internally do something like return(function() cachedValue)?
Now I am wondering if I can do this?
fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2))
shinyServer(function(input, output) {
currentFib <- reactiveValues({ fib(as.numeric(input$n)) })
output$nthValue <- renderText({ currentFib })
output$nthValueInv <- renderText({ 1 / currentFib })
})
Using
currentFib <- reactiveValues({ fib(as.numeric(input$n)) }) will not work in this context.
You will get an error saying that you are accessing reactive values outside of the "reactive context."
However, if you wrap it inside a function call instead, it will work:
currentFib <- function(){ fib(as.numeric(input$n)) }
This works because now the function call is inside a reactive context.
The key difference is the distinction they make in the Shiny documentation, between reactive "sources" and "conductors." In that terminology, reactive({...}) is a conductor, but reactiveValues can only be a source.
Here's how I think of reactiveValues - as a way to extend input which gets specified in UI.R. Sometimes, the slots in input are not enough, and we want derived values based on those input slots. In other words, it is a way to extend the list of input slots for future reactive computations.
Reactive() does what you say -- it returns the value, after re-running the expression each time any reactive Value changes. If you look at the source code for reactive you can see it:
The last line is that cached value that is being returned: Observable$new(fun, label)$getValue where 'fun' is the expression that was sent in the call to reactive.

Resources