You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny Dashboard删除变量时触发invalid argument to unary operator错误求助

Fixing the "invalid argument to unary operator" Error When Deleting Variables in Shiny Dashboard

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_var is 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_var is NULL or 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_var creates a logical vector to retain all columns except the selected ones.
  • drop = FALSE ensures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:17:27