过滤N个列以获取特定值

问题描述 投票:1回答:1

我有一个超过100个条件的大型数据帧作为布尔列(不是理想的设置,但我不能改变它)。我正在尝试创建一个带有可变数量条件列的函数,然后过滤所有条件为1或全部为零的过滤器。

建立

library(dplyr)
set.seed(123)
ID <- sample(1:5, 20, replace = TRUE)
Val <- round(runif(length(ID), 20, 40),0)
cond_1 <- sample(0:1, length(ID), replace = TRUE)
cond_2 <- sample(0:1, length(ID), replace = TRUE)
cond_3 <- sample(0:1, length(ID), replace = TRUE)
cond_4 <- sample(0:1, length(ID), replace = TRUE)


df <- data.frame(ID, Val, cond_1, cond_2, cond_3, cond_4, stringsAsFactors = FALSE)

任意两列的所需函数示例:

filterTwoCols <- function(df, cols){

  # Select desired conditions
  df1 <- df %>% 
    select(ID, Val, one_of(cols))

  #### Filter on all conditions == 0 or all conditions == 1
  df2 <- df1 %>% 
    filter(.[,ncol(.)] == 1 & .[,ncol(.) - 1] == 1 |
           .[,ncol(.)] == 0 & .[,ncol(.) - 1] == 0)

  return(df2)
}

filterTwoCols(df, c('cond_1', 'cond_4'))
filterTwoCols(df, c('cond_3', 'cond_2'))

我想要做的是命名任意数量的条件(例如filterManyCols(df, c('cond_1', 'cond_3', 'cond_4')),但我不知道如何在过滤器中明确命名它们(.[,ncol(.) - 2] == 1.[,ncol(.) - 3] == 1等)。如果选择的列数不匹配过滤器中的条件数,那么它将无法正常工作。有什么想法吗?

r dplyr
1个回答
2
投票

一个选择是filter_at

library(tidyverse)
filterManyCols <- function(df, cols){

 # Select desired conditions
 # Not clear whether we need to subset the columns or get the filtered 
 # full dataset columns
 # df <- df %>% 
 #       select(ID, Val, one_of(cols))

  map_df(0:1, ~ df %>%
                  filter_at(vars(one_of(cols)), all_vars(. == .x)))
 }

filterManyCols(df, c('cond_1', 'cond_4')) 
filterManyCols(df, c('cond_1', 'cond_2', 'cond_3'))   
filterManyCols(df, c('cond_1', 'cond_2', 'cond_3', 'cond_4'))
© www.soinside.com 2019 - 2024. All rights reserved.