r - R Shiny:根据输入小部件重新排列列
问题描述
我正在做一个项目,我需要从上传的数据集中选择一个特定的变量以位于第 1 列中。我创建了一个selectInput
inputwidget,它假设指定我希望位于第 1 列中的数据集中的哪个变量,但我在使用这个输入小部件时遇到了问题。
通常我会使用这样的代码来手动重新排列特定变量:
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)
解决方案
正如 Ben 指出的,答案可以在这里找到:将列移动到数据框中的第一个位置
“moveme”包已过时,但该setdiff()
功能可以完成工作。
这就是我最终使用的:
df <- df[c(input$col_1, setdiff(names(df),input$col_1))]
推荐阅读
- python - 基于逗号将单列的值打印到 d/f 列
- python-3.x - 数据透视表顺序
- javascript - MongoDB查找与数组的完全匹配
- spring-cloud-stream - spring-cloud-stream-binder-kafka-streams - 在功能实现中读取 Avro 消息
- python - 在多个处理器上执行时挂起的示例代码
- python-3.x - 添加与另一个数据框比较的 NaN 值
- python - Python Boolean:为什么在评估值和变量中类和类实例之间存在差异?
- python - 我可以在类声明中使用重载运算符吗?
- java - 无法在 Eclipse 控制台上打印结果
- java - 尝试使用 javac 编译 java 源代码:包 R 不存在