[英]Rename variable based on textInput value in Shiny
I want to update variable names in a dashboard based on value of textInput. 我想基于textInput的值更新仪表板中的变量名称。 I have prepared a reproducible example using mtcars dataset. 我已经使用mtcars数据集准备了一个可重现的示例。 I have commented out the areas where I was trying to rename, but did not work. 我已注释掉我要重命名的区域,但是没有用。
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)
You can use colnames() function to name the columns after your reactive datframe is generated. 您可以在生成反应式datframe之后使用colnames()函数命名列。 I added a req() statement in renderPrint() which avoids error when the app is loading. 我在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.