SAS: DATA step assignment (new = ...;, overwrite existing)
dplyr::mutate() adds or replaces columns. One call can set several columns. The result is a new data frame; the input is unchanged unless you overwrite it.
Quick reference
library (dplyr)
df |>
mutate (
AVAL = VALUE,
AVALC = as.character (VALUE)
)
mutate(NEW = expr)
DATA step new = expr;
mutate(VAR = expr)
overwrite existing variable
several columns in one mutate()
several assignments in one DATA step
Trap: mutate() returns a new table; assign it or pipe onward. It does not change the input object in place unless you overwrite the name.
Worked examples below.
Add a column
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
dm <- data.frame (
USUBJID = c ("STD-001-0001" , "STD-001-0002" ),
AGE = c (54 L, 61 L)
)
dm |>
mutate (AGEU = "YEARS" )
USUBJID AGE AGEU
1 STD-001-0001 54 YEARS
2 STD-001-0002 61 YEARS
SAS:
ageu = "YEARS";
Overwrite a column
dm |>
mutate (AGE = AGE + 1 L)
USUBJID AGE
1 STD-001-0001 55
2 STD-001-0002 62
Same name on the left replaces the column. Order matters when later columns use earlier ones in the same mutate().
Several columns
dm |>
mutate (
AGEU = "YEARS" ,
AGEGR1 = if_else (AGE < 65 L, "<65" , ">=65" )
)
USUBJID AGE AGEU AGEGR1
1 STD-001-0001 54 YEARS <65
2 STD-001-0002 61 YEARS <65
One mutate() is one DATA step block of assignments. Prefer that over chained one-column mutate() calls when the columns belong together.
mutate(dm, ...) alone does nothing lasting. Use dm <- dm |> mutate(...) or keep piping into the next verb.