0

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)

Wang
  • 1,314
  • 14
  • 21
  • 1
    The Shiny code might be superfluous here - the same error can be generated via something simple like: `library(data.table); df <- data.table("a" = 1, "b" = 2); nameofthecolumn <- "a"; df[, -(nameofthecolumn)]` – thelatemail Jun 18 '23 at 21:26
  • and just extending what @thelatemail points out, your `observeEvent()` can simply have `rv[[input$selectColumn]]<-NULL` – langtang Jun 18 '23 at 23:56
  • I think this is essentially a duplicate of this question - https://stackoverflow.com/questions/11940605/selecting-a-subset-of-columns-in-a-data-table - as per a couple of the answers there you can do `df[, -..nameofthecolumn]` or `df[, !..nameofthecolumn]` - if that solves it I'll close this as a duplicate. – thelatemail Jun 19 '23 at 01:12
  • @thelatemail thanks a lot for your help. I found out the problem. I need to add with = FALSE because the names are save in a variable in shiny. `df[, -(nameofthecolumn), with = FALSE]`. – Wang Jun 19 '23 at 06:18

0 Answers0