2017-03-29 122 views
0

我试图从用户上传的数据文件中动态填充selectInput的值。 selectInput只能包含数字列。在R中的selectInput中只显示一个值Shiny应用

这里是我的server.R

... 
idx <- sapply(data.file, is.numeric) 
numeric_columns <- data.file[, idx] 
factor_columns <- data.file[, !idx] 

updateSelectInput(session, "bar_x", "Select1", choices = names(numeric_columns)) 
updateSelectInput(session, "bar_y", "Select2", choices = names(factor_columns)) 
... 

代码片段对应ui.r

... 
selectInput("bar_x", "Select1", choices = NULL), 
selectInput("bar_y", "Select2", choices = NULL) 
... 

的代码工作正常,只要有任何下拉不止一个值。但是,只要遇到一个要显示在selectInput中的值,它就会失败。

如果数据已上传,并且如果只有一列为数字,则无法控制该数据,我该如何处理此特定条件?

回答

1

信息:代码由OP进行了修改,以使错误重现。 要解决您的问题,请使用val2 <- val[,idx, drop = FALSE] 您通过子集data.frame()删除了列名称。 要避免使用drop = FALSE;见Keep column name when select one column from a data frame/matrix in R

library(shiny) 

# Define UI for application that draws a histogram 
ui <- fluidPage(

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
     sidebarPanel(
# drj's changes START block 1 
     #selectInput('states', 'Select states', choices = c(1,2,4)) 
     selectInput('states', 'Select states', choices = NULL) 
# drj's changes END block 1 
    ), 

     # Show a plot of the generated distribution 
     mainPanel(
     plotOutput("distPlot") 
    ) 
    ) 
) 

# Define server logic required to draw a histogram 
server <- function(input, output, session) { 

    observe({ 


#drj's changes START block 2 
    #val <- c(1,2,3) 
    #names(val) <- c("a","b","c") 
    #updateSelectInput(session, 'states', 'Select states', choices = names(val[1])) 
    val <- as.data.frame(cbind(c("_1","_2","_3"), c(4, 4, 6))) 
    names(val) <- c("a","b") 
    val$b <- as.numeric(val$b) 
    idx <- sapply(val, is.numeric) 
    val2 <- val[,idx, drop = FALSE] 
    updateSelectInput(session, 'states', 'Select states', choices = names(val2)) 
#drj's changes END block 2 
    }) 
} 

# Run the application 
shinyApp(ui = ui, server = server) 
+0

我已更新您的代码,只需稍作修改即可。现在我终止了。希望你现在能够重现这个问题。 – Drj

+0

按预期工作。唯一我不明白的是,如果代码是在没有'drop'参数的控制台中手动运行的,它确实给了我预期的列名称。我最好的猜测是,在反应式代码块中将它作为参数传递是不一样的。 – Drj

+0

嗯,我无法重现,无法在控制台或我的工作 – BigDataScientist

相关问题