如何检查多个 R 列的值?
How to check multiple R columns for a value?
我有一个包含数百列的 R 数据框,其中可以包含一个数字。这些列都遵循如下命名方案:
1_parameter, 2_parameter, 3_parameter, ...
我想过滤上述任何列包含的行,比方说数字 97。我该怎么做,而不是使用像下面给出的 dplyr 命令那样的显式过滤器,我必须这样做明确地写每一列?:
filter(1_parameter==97 | 2_parameter==97 | ...)
像这样(假设你的数据被命名为 df
)
# get the column names that follow this pattern
cols = grepl("[0-9]+_parameter", names(df))
# see if any of those columns have a 97
any(df[cols] == 97)
过滤在任何这些列中具有 97 的行的基本 R 方法是:
df[rowSums(df[cols] == 97) > 0, ]
使用dplyr
:
df %>%
filter_at(vars(ends_with("_parameter")), any_vars(. == 97))
在新版本dplyr
中,选项为
library(dplyr)
library(purrr)
df %>%
filter(across(ends_with('parameter'), ~ . == 97) %>% reduce(`|`))
我有一个包含数百列的 R 数据框,其中可以包含一个数字。这些列都遵循如下命名方案:
1_parameter, 2_parameter, 3_parameter, ...
我想过滤上述任何列包含的行,比方说数字 97。我该怎么做,而不是使用像下面给出的 dplyr 命令那样的显式过滤器,我必须这样做明确地写每一列?:
filter(1_parameter==97 | 2_parameter==97 | ...)
像这样(假设你的数据被命名为 df
)
# get the column names that follow this pattern
cols = grepl("[0-9]+_parameter", names(df))
# see if any of those columns have a 97
any(df[cols] == 97)
过滤在任何这些列中具有 97 的行的基本 R 方法是:
df[rowSums(df[cols] == 97) > 0, ]
使用dplyr
:
df %>%
filter_at(vars(ends_with("_parameter")), any_vars(. == 97))
在新版本dplyr
中,选项为
library(dplyr)
library(purrr)
df %>%
filter(across(ends_with('parameter'), ~ . == 97) %>% reduce(`|`))