使用Shiny交互式输入过滤NA值无效及报错问题求助
Hey there! Let's sort out why your filter(!is.na()) isn't working and fix that error you ran into.
First, Why Isn't filter(!is.na()) Removing NAs?
There are a few common reasons this might happen:
- You didn't reassign the filtered dataset: If you just run
your_dataset %>% filter(!is.na(choiceDisplay1))without saving it to a new object (or overwriting the original), your plotting code is probably still using the unfiltered data. - You didn't specify the right variable: Maybe you forgot to target the exact column that has the NAs showing up in your plot (like
choiceDisplay1instead of another variable). - Multiple columns have NAs: If your plot uses multiple variables with missing values, you need to filter NAs from all of them, not just one.
Fixing the .choices Argument Error
That error you saw (supplied argument name '.choices' does not match...) is because filter() doesn't take a .choices parameter. You were overcomplicating it! Just pass the variable name directly to is.na().
Wrong:
filter(is.na(.choices=choiceDisplay1)) # Extra, invalid parameter here
Right:
filter(!is.na(choiceDisplay1)) # No extra params, just target the variable
Correct Ways to Filter NAs with dplyr
Here are practical examples tailored to your dataset (with gender, residency, SES, and choiceDisplay1):
1. Filter NAs from a single variable
If you only need to remove rows where choiceDisplay1 is NA:
library(dplyr) # Save the filtered data to a new object clean_data <- your_dataset %>% filter(!is.na(choiceDisplay1))
2. Filter NAs from multiple variables
If you want to remove rows where any of your key variables have NAs:
clean_data <- your_dataset %>% filter(across(c(gender, residency, SES, choiceDisplay1), ~!is.na(.x)))
Or use the simpler drop_na() function (dplyr's dedicated tool for this):
# Remove rows with NAs in specific columns clean_data <- your_dataset %>% drop_na(gender, residency, SES, choiceDisplay1) # Or remove rows with NAs in ANY column clean_data <- your_dataset %>% drop_na()
Verify the Filter Worked
Before plotting, double-check that NAs are gone:
# Check how many NAs are left in your target column sum(is.na(clean_data$choiceDisplay1)) # View a summary of all columns to confirm summary(clean_data)
Final Tip
Make sure your plotting code uses the clean_data object (not the original your_dataset)—that's a super common oversight!
内容的提问来源于stack exchange,提问作者Syrah.Sharpe

