I want to remove data columns in shiny.
I defined two removecolumn
functions. One is based on dplyr, and another is based on data.table.
See below:
#(1) use dplyr
removecolumn <- function(df, nameofthecolumn){dplyr::select(df, -all_of(nameofthecolumn))}
#(2) use data.table
removecolumn <- function(df, nameofthecolumn) {
df <- setDT(df) %>%
.[, -(nameofthecolumn)]
return(df)
}
However, the one based on data.table
is not working, and I got the follow error:
invalid argument to unary operator
How can I fix this error?
Here is my minimal example:
library(shiny)
library(data.table)
library(magrittr)
ui <- fluidPage(
titlePanel("CSV File Upload"),
sidebarLayout(
sidebarPanel(
fileInput("file", "Choose CSV file", accept = ".csv"),
uiOutput("selectColumn"),
actionButton("removeCol", "Remove"),
),
mainPanel(
tableOutput("table")
)
)
)
server <- function(input, output) {
rv <- reactiveValues(data = NULL)
observeEvent(input$file, {
rv$data <- read.csv(input$file$datapath, header = TRUE)
})
output$table <- renderTable({
rv$data
})
output$selectColumn <- renderUI({
shiny::req(rv$data)
selectInput(inputId = "selectColumn",
label = "Select sample(s) to remove",
multiple = TRUE,
choices = names(rv$data)
)
})
# removecolumn <- function(df, nameofthecolumn){dplyr::select(df, -all_of(nameofthecolumn))} works
# with data.table not working
removecolumn <- function(df, nameofthecolumn) {
df <- setDT(df) %>%
.[, -(nameofthecolumn)]
return(df)
}
observeEvent(input$removeCol, {
shiny::req(rv$data)
rv$data <- removecolumn(rv$data, input$selectColumn)
})
}
shinyApp(ui, server)