簡體   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