I'm doing a project where I need to select a specific variable from an uploaded dataset to be located in column 1.
I have created an selectInput
inputwidget that is suppose to specify which variable in the dataset that I want to be located in column 1, but I'm having trouble using this inputwidget.
Normally I would use a code like this to manually rearrange a specific variable:
df <- df[,c(names(df)[6],names(df)[-6])]
This will relocate the variable located in column 6 to column 1.
Of course, this code only work if the desired variable is located in column 6, which will not be the case in every dataset.
Using subsetting, I can't just replace the "6" with the inputwidget, since subsetting doesn't work on characters (as far as I know). I would like to avoid using an numeric inputwidget to specify the location of the variable, since I think the variable name is easier for a user to select, especially in a large dataset.
What is the easiest way of doing this?
Here is the app.
Note that right now, the selectInput widget doesn't do anything.
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="",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)
question from:
https://stackoverflow.com/questions/65846594/r-shiny-rearrange-columns-based-on-inputwidget