Select and rename

Keep, drop, and rename columns

SAS: KEEP, DROP, RENAME

select() chooses columns. rename() changes names without dropping others.

Quick reference

library(dplyr)

df |>
  select(USUBJID, AVAL, AVALC)

df |>
  select(-TEMP)

df |>
  rename(AVAL = VALUE)
R SAS
select(a, b) KEEP a b; (keep listed)
select(-a) DROP a;
rename(new = old) RENAME old = new; (note name order)

Trap: SAS RENAME old=new puts the old name first. dplyr::rename(new = old) puts the new name first.

Worked examples below.

Keep listed columns

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
ae <- data.frame(
  USUBJID = c("STD-001-0001", "STD-001-0001"),
  AETERM = c("NAUSEA", "HEADACHE"),
  AESEV = c("MILD", "MODERATE"),
  TEMP = c(1L, 2L)
)

ae |>
  select(USUBJID, AETERM, AESEV)
       USUBJID   AETERM    AESEV
1 STD-001-0001   NAUSEA     MILD
2 STD-001-0001 HEADACHE MODERATE

SAS: keep usubjid aeterm aesev;

Drop columns

ae |>
  select(-TEMP)
       USUBJID   AETERM    AESEV
1 STD-001-0001   NAUSEA     MILD
2 STD-001-0001 HEADACHE MODERATE

SAS: drop temp;

Rename

ae |>
  rename(AEDECOD = AETERM)
       USUBJID  AEDECOD    AESEV TEMP
1 STD-001-0001   NAUSEA     MILD    1
2 STD-001-0001 HEADACHE MODERATE    2
ImportantName order differs from SAS

SAS: rename aeterm = aedecod; (old = new).
R: rename(AEDECOD = AETERM) (new = old).

select(AEDECOD = AETERM, everything()) can rename and keep the rest in one step. Plain rename() is clearer when you only change names.