简体   繁体   中英

Conditionally subsetting and calculating a new variable in dataframe in shiny

I am trying to calculate a new variable in a dataframe in Shiny that is calculated conditionally on another variable.

Here's 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's 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's 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 Shiny code, I receive the following error:

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

I've tried different ways of subsetting and assigning, but I'm stuck. Your help is greatly appreciated!

I'm not sure that you're clear on what reactive() is doing... I'd recommend reading a bit more of the shiny documentation, and in particular to have a look at the examples - '03_reactivity' would probably be a good one.

Regardless, here is how your code can be adapted to do what you want. It's not the best way to do this, but hopefully it will help you see where there are problems at the moment.

I've only changed the server.R file, and haven't changed any of the code for how you're constructing the new variable. The code to construct the new variable goes inside a reactive function - you then need to call the function to actually make the 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()
  })

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM