Conditionally subset and computing a new variable in a dataframe in brilliant

I am trying to compute a new variable in a data frame in Shiny, which is computed conditionally on another variable.

Here is a small example of what I'm trying to do:

mydata <- data.frame(cbind(x = 1, y = 1:10)) value <- 10 #from user input mydata$z[mydata$y >= 5] <- mydata$y[mydata$y >= 5] + value mydata$z[mydata$y < 5] <- mydata$y[mydata$y < 5] - value 

Here is my ui.R file:

 #Library library("shiny") # Define UI for miles per gallon application shinyUI(pageWithSidebar( # Application title headerPanel("Test"), sidebarPanel( numericInput("value", "Enter Value:", 10) ), mainPanel( tableOutput("table") ) ) ) 

Here is my server.R file:

 #Libraries library(shiny) #Load Data mydata <- data.frame(cbind(x = 1, y = 1:10)) # Define server logic shinyServer(function(input, output) { mydata$z[mydata$y >= 5] <- reactive({ mydata$y + input$value }) mydata$z[mydata$y < 5] <- reactive({ mydata$y - input$value }) output$table <- renderTable({ mydata }) }) 

With this brilliant code, I get the following error:

Error in mydata $ z [mydata $ y> = 5] <- reactive ({: invalid type / length (closure / 0) in vector distribution

I tried different ways of subset and assignment, but I'm stuck. Your help is much appreciated!

+2
r shiny dataframe
source share
1 answer

I'm not sure if you know what reactive() does ... I would recommend reading a little more documentation on shiny and, in particular, looking at examples - 03_reactivity 'will probably be good.

No matter how your code can be adapted to do what you want. This is not the best way to do this, but hopefully it helps you see where there are problems at the moment.

I just changed the server.R file and did not change the code for how you build the new variable. The code for creating a new variable is included in the reactive function - then you need to call the function to actually make the table.

 #Libraries library(shiny) #Load Data mydata <- data.frame(cbind(x = 1, y = 1:10)) # Define server logic shinyServer(function(input, output) { newdata <- reactive({ mydata$z[mydata$y >= 5] <- mydata$y[mydata$y >= 5] + input$value mydata$z[mydata$y < 5] <- mydata$y[mydata$y < 5] - input$value return(mydata) }) output$table <- renderTable({ newdata() }) }) 
+6
source share

All Articles