This function renames specified columns in a data frame based on a named vector of new column names. It performs checks to ensure that the new names are valid and that the columns to rename exist in the data frame.

rename_columns(df, new_names)

Arguments

df

A data frame in which columns are to be renamed.

new_names

A named vector where the names correspond to the existing column names and the values are the new column names.

Value

The data frame with renamed columns.

Examples

# Create a sample data frame
df <- data.frame(
  old_col1 = c(1, 2, 3),
  old_col2 = c(4, 5, 6),
  old_col3 = c(7, 8, 9)
)

# Define the new column names
new_names <- c("old_col1" = "new_col1", "old_col2" = "new_col2")

# Rename the columns
renamed_df <- rename_columns(df, new_names)
print(renamed_df)
#>   new_col1 new_col2 old_col3
#> 1        1        4        7
#> 2        2        5        8
#> 3        3        6        9