【发布时间】:2021-04-27 00:07:17
【问题描述】:
我正在做一个项目,我需要从上传的数据集中选择一个特定变量以位于第 1 列中。
我创建了一个selectInput inputwidget,它假设指定我希望在第 1 列中定位数据集中的哪个变量,但是我在使用这个 inputwidget 时遇到了问题。
通常我会使用这样的代码来手动重新排列特定变量:
df <- df[,c(names(df)[6],names(df)[-6])]
这会将位于第 6 列的变量重新定位到第 1 列。 当然,此代码仅在所需变量位于第 6 列时才有效,并非在每个数据集中都如此。
使用子集,我不能只用输入小部件替换“6”,因为子集不适用于字符(据我所知)。我想避免使用数字输入小部件来指定变量的位置,因为我认为变量名称更容易让用户选择,尤其是在大型数据集中。
最简单的方法是什么?
这是应用程序。 请注意,现在,selectInput 小部件不执行任何操作。
ui <- fluidPage(
navbarPage(title = "Rearrange columns in shiny R",
tabPanel("Upload file",
br(),
sidebarPanel(
fileInput(inputId = "file1", label="Upload file"),
textOutput("dataset_info"),
br(),
uiOutput("col_1"),
hr(),
checkboxInput(inputId ="header", label="header", value = TRUE),
checkboxInput(inputId ="stringAsFactors", label="stringAsFactors", value = TRUE),
radioButtons(inputId = "sep", label = "Seperator", choices = c(Comma=",",Semicolon=";",Tab="\t",Space=" "), selected = ","),
radioButtons(inputId = "disp", "Display", choices = c(Head = "head", All = "all"), selected = "head"),
), # End sidebarPanel
mainPanel(
tableOutput("contents"),
textOutput("display_info")
)# End mainPanel
))) # EndtabPanel "upload file"
server <- function(input, output, session) {
# Upload file content table
get_file_or_default <- reactive({
if (is.null(input$file1)) {
paste("No file is uploaded yet, please select a file.")
} else {
df <- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
output$dataset_info <- renderText(paste(dim(df)[2],"variables,",dim(df)[1],"obsevations."))
if(input$disp == "head") {
output$display_info <- renderText(paste("Showing 18 out of",dim(df)[1],"obsevations..."))
return(head(df, 18))
}
else {
return(df)
}
}
})
output$contents <- renderTable(get_file_or_default())
# Select column 1 variable
output$col_1 <- renderUI({
req(input$file1)
if (is.null(input$file1)) {} else {
df <- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
selectInput(inputId = "col_1",
label= "Variable to be in column 1",
choices = names(df),
selected = names(df)[1])
}
})
}
shinyApp(ui, server)
【问题讨论】:
-
in this post 选项之一对您有帮助吗?
-
这行得通,谢谢!尽管他的“moveme”包似乎已经过时,但使用 setdiff() 函数的示例运行良好,因为它允许将 inputwidget 用作参数。