Reputation:
I'm new to R/Shiny, and am trying to get my head around reactivity. Both this article and this video have been helpful resources so far, but I've bumped up against something I don't quite understand.
Here's a simplified version of the code I was running.
library(shiny)
some_func <- function(some_input, unused_argument) {
print("Running - you changed something")
if (some_input) {1} else {-1}
}
ui <- fluidPage(
checkboxInput("negative", "Clicking makes all values negative"),
checkboxInput("negative_pt2", "I thought clicking would not change results
other than writing to the console,
but it does not even do that."),
plotOutput("graphs")
)
server <- function(input, output) {
library(ggplot2)
output$graphs <- renderPlot({
dataset2 <- reactive({mtcars * some_func(input$negative, input$negative_pt2)})
ggplot(dataset2(), aes(x = mpg, y = hp)) + geom_line()
})
}
shinyApp(ui = ui, server = server)
Checking the first box has the expected results. But viewing the console when checking the second one shows that Shiny is clever enough to realize that my unused argument is useless. This is great, but how does it know to do this?
Thanks!
Upvotes: 0
Views: 2457
Reputation: 3000
You are not calling the second argument within your function, therefore it will not do anything
I can write a function that requires the user to input a million variables, but If I do not call them whitin the function itself, they will never be used
some_func <- function(some_input, unused_argument) {
print("Running - you changed something")
if (some_input) {1} else {-1}
}
.....
some_func(input$negative, input$negative_pt2)
Yes, the variable is placed in the function in the unused argument spot, but then it's never used, so it just sits around.
If we change our function to do something with the variable it collects, then we would have a change.
some_func <- function(some_input, unused_argument) {
print("Running - you changed something")
if (some_input) {1} else {**unused_argument**}
}
Shiny is assigning a value to negative_pt2, but you never say, "hey, do something based off that variable", so it just sits around.
Moral of the story, you not only need to take in variables, but also use them in the function for them to have an effect.
Upvotes: 1