R语言:统计数据框特定值生成布尔计数表及报错解决
Hey there! Let's sort out this counting problem for you. First, let's recap your data setup so we're all on the same page:
library(dplyr) df <- data.frame(letters = letters) %>% mutate(letters = as.character(letters)) df[3,1] <- "" df[5,1] <- "" df[8,1] <- "Unknown"
Why your original code failed
The error happens because which() expects a single logical vector as input, but your syntax is passing multiple arguments incorrectly. Instead of trying to filter the existing table(df) output, it's simpler to first create a logical flag for your target values, then count those flags.
Solution 1: Base R (simple & straightforward)
First, create a logical vector that marks whether each value is either "" or "Unknown", then use table() to count the TRUE/FALSE cases:
# Create a logical indicator for target values is_match <- df$letters %in% c("", "Unknown") # Count the occurrences result_table <- table(is_match) result_table
This will output exactly what you're looking for:
is_match FALSE TRUE 23 3
If you want the labels to be capitalized ("False" instead of "FALSE", "True" instead of "TRUE"), you can adjust the factor levels:
result_table_named <- table( factor(is_match, levels = c(FALSE, TRUE), labels = c("False", "True")) ) result_table_named
Solution 2: Tidyverse/dplyr approach
If you prefer working with dplyr, you can use mutate() to add the logical flag and count() to tally, or directly summarize the counts:
Option 2a: Using count()
df %>% mutate(is_match = letters %in% c("", "Unknown")) %>% count(is_match) %>% mutate(is_match = ifelse(is_match, "True", "False"))
Option 2b: Direct summary (gives exact "True:3, False:23" style output)
df %>% summarise( True = sum(letters %in% c("", "Unknown")), False = n() - True )
This will return a data frame with one row and two columns, showing your desired counts directly.
内容的提问来源于stack exchange,提问作者Doug Fir

