R Shiny Dashboard删除变量时触发invalid argument to unary operator错误求助
Hey there! Let's break down why you're seeing that frustrating error and how to fix it.
What's Causing the Error?
The Warning: Error in -: invalid argument to unary operator message pops up because you're trying to use the negative unary operator (-) on something that isn't a valid numeric index. Here are the two most likely scenarios:
- Your
input$miss_varis returning variable names (character strings) instead of column numbers, and you can't subtract character values directly with-. - No variables are selected, so
input$miss_varisNULLor an empty vector—using-on an empty value is invalid.
Step-by-Step Fixes
1. Handle Character-Based Variable Selections
If your UI's miss_var control (like a selectInput) returns variable names (the default behavior), replace your existing code with this approach that targets columns by name:
if(input$imputation == "Delete Variable"){ # Only run deletion if variables are actually selected if(!is.null(input$miss_var) && length(input$miss_var) > 0){ # Keep columns that are NOT in the selected list rv$Train <- rv$Train[, !colnames(rv$Train) %in% input$miss_var, drop = FALSE] } return(rv$Train) }
- The
!colnames(rv$Train) %in% input$miss_varcreates a logical vector to retain all columns except the selected ones. drop = FALSEensures your data stays as a data frame (instead of converting to a vector) if you end up with only one column left after deletion.
2. Ensure Your UI Supports Multiple Selections
Double-check that your miss_var input allows users to select multiple variables. For example, if you're using selectInput, add multiple = TRUE:
selectInput( inputId = "miss_var", label = "Select Variables to Delete:", choices = colnames(rv$Train), # Dynamically load column names from your dataset multiple = TRUE )
3. (Optional) If Using Numeric Indexes
If you intentionally set up your UI to return numeric column indexes (less common), you still need to add a check for empty selections to avoid errors:
if(input$imputation == "Delete Variable"){ if(!is.null(input$miss_var) && length(input$miss_var) > 0){ rv$Train <- rv$Train[, -input$miss_var, drop = FALSE] } return(rv$Train) }
Why This Works
By adding the check for non-empty selections, you avoid trying to perform arithmetic on a NULL value. And by targeting columns by name (or properly validating numeric indexes), you eliminate the unary operator mismatch that was triggering the error.
内容的提问来源于stack exchange,提问作者Balaji N

