R Shiny:在反应式数据框中创建新列 [英] R Shiny: Creating New Columns Within a Reactive Data Frame

查看:44
本文介绍了R Shiny:在反应式数据框中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 summarized 的数据框,其中包括 TY_COMPLY_COMP 列(等等).我可以在 R 中编写一个函数,对 TY_COMPLY_COMP 执行计算,并在数据框中创建一个名为 cac 的新列,如下所示:

Say I have a data frame called summarized which includes the columns TY_COMP and LY_COMP (among others). I could write a function in R that performs a calculation on TY_COMP and LY_COMP and creates a new column called cac in the data frame like this:

summarized$cac <- summarized$TY_COMP/summarized$LY_COMP-1

cac 现在是汇总数据框中的一个新列.

cac is now a new column in the summarized data frame.

现在说 summarized() 是一个具有相同列的反应式数据框.

Now say that summarized() is a reactive data frame with the same columns.

如何实现在非反应数据框中完成的效果,即在当前帧中创建一个新列?或者我怎么会得到同样的效果?

How could I achieve the effect done in the non-reactive data frame, i.e. create a new column within the current frame? Or how would I get the same effect?

我试过了:

summarized$cac <- reactive({summarized()$TY_COMP/summarized()$LY_COMP-1})

推荐答案

我想你想修改一个 reactive 例如当一个 actionButton 被点击时.为此,我将使用 reactiveValues.您可以在诸如 observeobserveEvent 之类的观察者内部修改 reactiveValue.

I reckon you want to modify a reactive when for example an actionButton is clicked. For this purpose I would use reactiveValues. You can modify reactiveValue inside of observers such as observe or observeEvent.

看看这个简单的例子:

summarized <- data.frame(id = 1:20, group = letters[1:4], TY_COMP = runif(20), LY_COMP = runif(20))

library(shiny)

ui <- fluidPage(
  verbatimTextOutput("text"),
  actionButton("btn", "Add the 'cac' column to summarized")
)

server <- function(input, output){
  rv <- reactiveValues(summarized = summarized)

  output$text <- renderPrint(rv$summarized)

  observeEvent(input$btn, {
    rv$summarized$cac <- summarized$TY_COMP / summarized$LY_COMP - 1
  })

  summarized_mod <- reactive({
    summarized()$TY_COMP / summarized()$LY_COMP-1
  })
}

shinyApp(ui, server)

另一种选择是创建另一个具有附加列的 reactive.这可以使用,但根据您的用例,我推荐第一种解决方案.

Another option would be to create another reactive that has an additional column. This is possible to use, but depending on your use case, I recommend the first solution.

示例:

summarized <- data.frame(id = 1:20, group = letters[1:4], TY_COMP = runif(20), LY_COMP = runif(20))

library(shiny)

ui <- fluidPage(
  verbatimTextOutput("text1"),
  verbatimTextOutput("text2")
)

server <- function(input, output){

  output$text1 <- renderPrint(summarized_orig())
  output$text2 <- renderPrint(summarized_mod())


  summarized_orig <- reactive( {
    summarized
  })

  summarized_mod <- reactive({
    df <- summarized_orig()
    df$cac <- summarized_orig()$TY_COMP / summarized_orig()$LY_COMP - 1

    df
  })
}

shinyApp(ui, server)

这篇关于R Shiny:在反应式数据框中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆