R语言:如何筛选任意列含指定值的行?支持数值与字符串
Hey there! Let's work through this problem together. First, let's recreate the dataset using your provided code to make sure we're on the same page:
set.seed(1234) m3 <- matrix(12:1,nrow=6,ncol=4) m4 <- as.data.frame(m3) m5 <- m4[sample(nrow(m4)),]
Solution 1: Base R (works for both numeric and string columns)
We can use rowSums() combined with sapply() to check if any element in a row matches your target values (12, 9, 7). This approach works seamlessly for string data too—just adjust your target values to strings when needed.
# Define your target values (use strings like c("12", "9", "7") for string columns) target_values <- c(12, 9, 7) # Filter rows where ANY column contains a target value filtered_m5 <- m5[rowSums(sapply(m5, function(col) col %in% target_values)) > 0, ]
Here's what's happening:
sapply(m5, function(col) col %in% target_values)creates a logical matrix where each cell isTRUEif the element matches a target value, otherwiseFALSE.rowSums()converts those logical values to 1s and 0s, then sums them per row. A sum greater than 0 means at least one element in the row is a match.
Solution 2: Alternative Base R with apply()
If you prefer a more explicit row-wise check, use apply() with any():
filtered_m5 <- m5[apply(m5, 1, function(row) any(row %in% target_values)), ]
This iterates over each row and checks if any element in the row is in your target list—again, works for both numeric and string data.
Solution 3: Tidyverse (dplyr) for cleaner syntax
If you're using the tidyverse, if_any() makes this super intuitive and readable:
library(dplyr) filtered_m5 <- m5 %>% filter(if_any(everything(), ~ .x %in% target_values))
if_any(everything(), ...) tells dplyr to check every column, and keep rows where at least one column meets the condition (~ .x %in% target_values). This method also supports both numeric and string columns without any extra adjustments.
Testing with string columns
To confirm this works for strings, just convert your dataset to string type and update the target values:
# Convert m5 to string columns m5_str <- m5 %>% mutate(across(everything(), as.character)) # Use string targets target_strings <- c("12", "9", "7") # Same filter code works! filtered_m5_str <- m5_str %>% filter(if_any(everything(), ~ .x %in% target_strings))
All these methods will give you the rows where any column contains your target values, and they're fully adaptable to string data as requested.
内容的提问来源于stack exchange,提问作者Mark

