Rename columns in a data frame and tibble based on a dictionary
Source:R/dta_rename.R
dta_rename.Rd
dta_rename()
renames columns in a data frame dat
using
a dictionary dict
. The dictionary specifies the old column names and
their corresponding new names.
Details
The function checks the following:
Both
dat
anddict
are data frames or tibbles.Columns specified in
.oldnames
exist indict
.The new variable names
.newnames
are unique.There is no overlap between
.oldnames
and.newnames
to avoid conflicts.
If any issues are detected, an error or warning is raised to ensure proper processing.
Examples
data("data_bmi")
dta_gtable(data_bmi)
# Rename the columns `age` and `weight` to `age_in_years`
# and `weight_in_kgs`
result <- dta_rename(
dat = data_bmi,
.oldnames = c("age", "weight"),
.newnames = c("age_in_years", "weight_in_kgs")
)
dta_gtable(result)
# Rename all columns to `unique_id`, `age_in_years`,
# `height_in_meters` and `weight_in_kgs`. In this case,
new_names <- c(
"unique_id",
"age_in_years",
"height_in_meters",
"weight_in_kgs"
)
result2 <- dta_rename(
dat = data_bmi,
.oldnames = NA,
.newnames = new_names
)
dta_gtable(result2)
# Rename from a dictionary - Begin by loading the dataset
# with columns to be renamed.
data("data_rename")
dta_gtable(head(data_rename))
# The dictionary with the columns `oldnames` and
# `newnames` representing the old and new variable names
# respectively
data("dict_rename")
dta_gtable(dict_rename)
# Perform the renaming
result3 <- dta_rename(
dat = data_rename,
dict = dict_rename,
.oldnames = old,
.newnames = new
)
dta_gtable(result3)