Filter

Keep rows that match a condition

SAS: WHERE, subsetting IF

dplyr::filter() keeps rows for which the condition is TRUE.

Quick reference

library(dplyr)

df |>
  filter(PARAMCD == "SYSBP")

df |>
  filter(PARAMCD == "SYSBP", !is.na(AVAL))
R SAS
filter(cond) where cond; or subsetting if cond;
filter(a, b) where a and b; (both must be true)
filter(a \| b) where a or b;

Trap: filter() keeps rows where the condition is TRUE. Rows with NA in the condition are dropped. SAS where also treats missing as not true for most comparisons.

Worked examples below.

One condition

library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
vs <- data.frame(
  USUBJID = c("STD-001-0001", "STD-001-0001", "STD-001-0002"),
  PARAMCD = c("SYSBP", "DIABP", "SYSBP"),
  AVAL = c(120, 80, NA_real_)
)

vs |>
  filter(PARAMCD == "SYSBP")
       USUBJID PARAMCD AVAL
1 STD-001-0001   SYSBP  120
2 STD-001-0002   SYSBP   NA

SAS: where paramcd = "SYSBP";

Several conditions

vs |>
  filter(PARAMCD == "SYSBP", !is.na(AVAL))
       USUBJID PARAMCD AVAL
1 STD-001-0001   SYSBP  120

Commas in filter() mean AND. Use | for OR.

ImportantNA in the condition drops the row

filter(AVAL > 100) drops rows where AVAL is NA, because NA > 100 is not TRUE. Keep missing values on purpose with is.na(AVAL) | AVAL > 100 when that is the rule.