繁体   English   中英

根据Shiny中的textInput值重命名变量

[英]Rename variable based on textInput value in Shiny

我想基于textInput的值更新仪表板中的变量名称。 我已经使用mtcars数据集准备了一个可重现的示例。 我已注释掉我要重命名的区域,但是没有用。

library(shiny)
library(dplyr)

ui <- fluidPage(
  fluidRow(
    column(
      4, 
      selectInput("x", "select x variable", colnames(mtcars), "mpg"),
      selectInput("y", "select y variable", colnames(mtcars), "wt"),
      br(),
      uiOutput("xxx"),
      uiOutput("yyy")
    ),
    column(
      8,
      verbatimTextOutput("summary")
    )
  )
)

server <- function(input, output, session) {

  output$xxx <- renderUI({
    textInput("xlab", "Rename x variable", value = input$x)
  })

  output$yyy <- renderUI({
    textInput("ylab", "Rename y variable", value = input$y)
  })

  # df <- reactive({
  #   select(mtcars, input$x, input$y) %>%
  #     rename(input$xlab = input$x, input$ylab = input$y)
  # })

  output$summary <- renderPrint({
    select(mtcars, input$x, input$y) %>% summary()
    # df() %>% summary()
  })
}

shinyApp(ui, server)

您可以在生成反应式datframe之后使用colnames()函数命名列。 我在renderPrint()中添加了req()语句,以避免在加载应用程序时出错。

library(shiny)
library(dplyr)

ui <- fluidPage(
  fluidRow(
    column(
      4, 
      selectInput("x", "select x variable", colnames(mtcars), "mpg"),
      selectInput("y", "select y variable", colnames(mtcars), "wt"),
      br(),
      uiOutput("xxx"),
      uiOutput("yyy")
    ),
    column(
      8,
      verbatimTextOutput("summary")
    )
  )
)

server <- function(input, output, session) {

  output$xxx <- renderUI({
    textInput("xlab", "Rename x variable", value = input$x)
  })

  output$yyy <- renderUI({
    textInput("ylab", "Rename y variable", value = input$y)
  })

  df <- reactive({
    df.selected <- select(mtcars, input$x, input$y) 
    #colnames(df.selected) <- c(input$xlab, input$ylab)

    # Edit - Keep original column names if textInputs are empty 
    # func.for.colnames <- function(){ 
    #   if (!isTruthy(input$xlab) | !isTruthy(input$xlab)){  
    #     return(c(input$x, input$y))
    #   }
    #   
    #   else {
    #     return(c(input$xlab, input$ylab))
    #   }}
    # 
    # colnames(df.selected) <- func.for.colnames()

    # Edit2 - Above function is too complicated. The following works flawlessly
    if(isTruthy(input$xlab)) {
      colnames(df.selected)[1] <- input$xlab
    }
    if(isTruthy(input$ylab)) {
      colnames(df.selected)[2] <- input$ylab
    }

    df.selected

  })

  output$summary <- renderPrint({
    # req(input$xlab) # Unnecessary
    summary(df())
  })
}

shinyApp(ui, server)

暂无
暂无

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

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