简体   繁体   English

dplyr使用ifelse过滤数据帧变量的值?

[英]dplyr filter values of a dataframe variable using ifelse?

I have a dataframe: 我有一个数据帧:

structure(list(a = c(1, 2, 3), b = c(TRUE, TRUE, FALSE)), .Names = c("a", 
"b"), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))

and a function: 和功能:

foo <- function(df, L = TRUE) {

    return(df %>% filter(ifelse(L, b, !b))) }

When I run it, it seems that ifelse doesn't do the job. 当我运行它时,似乎ifelse不能完成这项工作。 Please advise how can I "tell" the function to filter for all TRUE's if L is TRUE and FALSE's otherwise? 如果L为TRUE,请告知如何“告诉”过滤所有TRUE的函数,否则为FALSE?

The ifelse needs a vectorize argument when used with dplyr::filter or dplyr::mutate . 当与dplyr::filterdplyr::mutate一起使用时, ifelse需要一个vectorize参数。 That means the condition should be a vector of length matching with row numbers provided to ifelse as condition is evaluated for each row. 这意味着condition应该是长度与向ifelse提供的行号匹配的向量,因为对每行计算condition

You can modify your function to provide L as below: 您可以修改您的功能以提供如下L

library(dplyr)

foo <- function(df, L = TRUE) {
  # replicate the condition to match number of rows
  return(df %>% filter(ifelse(rep(L,nrow(.)), b, !b))) 
  }

Now verify results: 现在验证结果:

foo(df)
# # A tibble: 2 x 2
# a b    
# <dbl> <lgl>
# 1  1.00 T    
# 2  2.00 T    

foo(df,FALSE)
# # A tibble: 1 x 2
# a b    
# <dbl> <lgl>
# 1  3.00 F 

What about this in base R? 基地R怎么样?

foo <- function(df, L = TRUE) {
  if (L == TRUE) return(df[df$b == TRUE, ])
  else return(df[df$b == FALSE, ])
}

Yielding 生产

> foo(df, L=TRUE)
# A tibble: 2 x 2
      a b    
  <dbl> <lgl>
1     1 TRUE 
2     2 TRUE 
> foo(df, L=FALSE)
# A tibble: 1 x 2
      a b    
  <dbl> <lgl>
1     3 FALSE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM