【问题标题】:using if within filter_at()在 filter_at() 中使用 if
【发布时间】:2020-01-21 21:38:45
【问题描述】:

数据

df <- structure(list(ID = c("51-07519", "51-07522", "51-07525", "51-07526", 
    "51-07527", "51-07530"), name = c("Fyb", "Fyb", "Fyb", "Fyb", 
    "Fyb", "Fyb"), serology_charts = c(0L, 0L, NA, 0L, 1L, 1L), antibodies_chart = c(NA_integer_, 
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
    ), bioarray_charts = c(NA, 0L, NA, 0L, NA, NA), others_charts = c(NA_integer_, 
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
    ), Fyb = c(1, 1, 1, 1, 1, 1), GATAfactor = c(0, 0, 1, 0, 0.5, 
    0.5)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
    ))

我目前运行以下过滤器:

df%>% 
     filter_at(vars(ends_with("charts")), any_vars(!is.na(.) & . != Fyb*GATAfactor))

是否可以这样写if语句:

if Fyb!=1  {filter_at(vars(ends_with("charts")), any_vars(!is.na(.) & . != Fyb))}
else       {filter_at(vars(ends_with("charts")), any_vars(!is.na(.) & . != Fyb*GATAfactor))}

【问题讨论】:

    标签: r filter dplyr


    【解决方案1】:

    我们可以将条件包装在 case_whenifelse

    library(dplyr)
    df %>%
      filter_at(vars(ends_with("charts")),
          any_vars(case_when(Fyb == 1 ~  !is.na(.) & . != Fyb*GATAfactor, 
          TRUE ~ !is.na(.) & . != Fyb)))
    

    或使用ifelse

    df %>%
        filter_at(vars(ends_with("charts")),
           any_vars(ifelse(Fyb == 1, !is.na(.) & . != Fyb*GATAfactor, !is.na(.) & . != Fyb)))
    

    【讨论】:

    • ifelse 会是什么样子?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    相关资源
    最近更新 更多