R Shiny - 如何将字符串和数字连接到新字符串并打印

时间:2016-08-30 14:13:52

标签: r shiny

我有以下问题:我想写一个闪亮的应用程序,允许输入变量名称(例如" test")和数字(例如" 5"),以便这些变量名称的向量从1输入到输入数字(" test1"," test2"," test3"," test4", " test5")显示。但不知怎的,它不起作用。

server.r:

library(shiny)

server <- function(input,output){

  output$varName<-renderUI({
      textInput("name", "Variable Name", value = "test")
  })

  output$number<-renderUI({
      numericInput("number", "Number", value = 5, min = 0, max = 10)
  })

  connect=reactive({
      name<-input$name
      n<-input$number
      var.names<-rep(name, n)
      var.names.n<-paste(var.names,seq(1:n),sep=",")
  })

  output$view <- renderPrint({
      connect()$var.names.n
  })

}

和ui.r:

library(shiny)

shinyUI(pageWithSidebar(

  headerPanel("Set Variable Names"),

  sidebarPanel(
    uiOutput("varName"),
    uiOutput("number")
  ),

  mainPanel(
    textOutput("view")
  )
))

如果有人能看一眼,会非常感激:)

非常感谢!

2 个答案:

答案 0 :(得分:0)

你的connect()什么都不返回

1)添加return to connect reactive

2)编辑渲染打印

3)添加检查输入是否存在

4)添加检查输入$ number是否大于0

实施例

connect=reactive({
    if(!is.null(input$name) & ! is.null(input$number) ){
      if(input$number>0){
      name<-input$name
      n<-input$number
      var.names<-rep(x=name, times=n)
      var.names.n<-paste(var.names,seq(1:n),sep="")
      return(var.names.n)
      }
    }
  })

  output$view <- renderPrint({

    connect()
  })

答案 1 :(得分:0)

感谢@Batanichek进行is.null条件检查,这解决了初始错误。

ui.r:

library(shiny)

shinyUI(pageWithSidebar(

  headerPanel("Set Variable Names"),

  sidebarPanel(
    uiOutput("varName"),
    uiOutput("number")
  ),

  mainPanel(
    textOutput("view")
  )
))

server.r:

library(shiny)

server <- function(input,output){

  output$varName<-renderUI({
    textInput("varName", "Variable Name", value = "test")
  })

  output$number<-renderUI({
    # please note that an input value of 0 will cause a problem below.
    numericInput("number", "Number", value = 5, min = 0, max = 10)
  })

  connect<-reactive({

    if(!is.null(input$varName) && ! is.null(input$number) ){
    name<-input$varName
    n<-input$number
    var.names<-rep(name, n)
    var.names.n<-paste(var.names,seq(1:n),sep="")
    return (var.names.n)
    }
  })

  output$view <- renderPrint({
    connect()
  })

}