简体   繁体   English

有条件地在数据帧中对闪亮的新变量进行子集化和计算

[英]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. 我试图在Shiny中的数据帧中计算一个新变量,该变量是在另一个变量上有条件地计算的。

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: 这是我的ui.R文件:

#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: 这是我的server.R文件:

#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 mydata $ z [mydata $ y> = 5] < - reactive({:向量分配中的无效类型/长度(闭包/ 0)错误

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. 我不确定你是否清楚reactive()正在做什么......我建议你阅读一些更有shiny文档,特别是看看这些例子 - '03_reactivity'可能是一个好的。

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. 我只更改了server.R文件,并没有更改任何代码来构建新变量。 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. 构造新变量的代码进入reactive函数 - 然后需要调用函数来实际创建表。

#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()
  })

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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