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

时间:2018-07-15 09:19:06

标签: r dataframe dplyr

我有一个数据框:

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"
))

和一个功能

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

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

当我运行它时,ifelse似乎无法完成工作。 请告知如果L为TRUE,否则我如何“告诉”该函数以筛选所有TRUE,否则为FALSE?

2 个答案:

答案 0 :(得分:2)

ifelsedplyr::filterdplyr::mutate一起使用时需要向量化参数。这意味着condition应该是长度与向ifelse提供的行号匹配的向量,因为对每一行都评估了condition

您可以修改功能以提供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))) 
  }

现在验证结果:

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 

答案 1 :(得分:1)

在基数R中呢?

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

屈服

> 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
相关问题