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

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 is TRUE if the element matches a target value, otherwise FALSE.
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:52:38