srename {labelr} | R Documentation |
Safely Rename a Variable and Preserve Its Value Labels
Description
Note: srename
renames and existing variable and preserves its value labels,
overwriting an existing variable only if option force = TRUE.
Usage
srename(data, old.name, new.name, force = FALSE)
Arguments
data |
a data.frame. |
old.name |
the unquoted name of the existing variable being renamed (to new.name). |
new.name |
the unquoted name that will be used to rename the variable specified in the old.name argument. |
force |
if a variable with the same name as new.name already exists in the data.frame, allow it to be overwritten. If FALSE, this will not be allowed, and an error will be issued. |
Details
Any non-labelr R operation that changes a variable's (column's) name or that
copies its contents to another variable (column) with a different name will
not associate the original variable's value labels with the new variable name.
To mitigate this, srename
allows one to rename a data.frame variable while
preserving its value labels – that is, by associating the old.name's value
labels with the new.name. If the old.name variable (column) has a name label
(in "name.labs" attribute), the column name associated with that name label
will be changed from old.name to new.name.
Value
A data.frame.
Examples
# make toy demographic (gender, raceth, etc.) data set
set.seed(555)
df <- make_demo_data(n = 1000) # another labelr:: function
# let's add variable VALUE labels for variable "raceth"
df <- add_val_labs(df,
vars = "raceth", vals = c(1:7),
labs = c("White", "Black", "Hispanic", "Asian", "AIAN", "Multi", "Other"),
max.unique.vals = 50
)
head(df, 4)
df <- srename(df, old.name = gender, new.name = genid)
df <- srename(df, old.name = raceth, new.name = racid)
df <- srename(df, old.name = x1, new.name = var1)
head(df, 4)