This function will rename a selection of columns as, for example, var_1, var_2, var_2 ... var_10, where the prefix, var in this example, is arbitrary.

rename_with_seq(data_df, col_selector, prefix = "var")

Arguments

data_df

A data frame

col_selector

A tidy selector, e.g. contains('foo'), ends_with('bar').

prefix

The prefix for the sequence, e.g. 'drug' to produce names like drug_1, drug_2 etc.

Value

A data frame with renamed columns

Details

If we had, for example, a data frame where columns were the names of drugs and we wanted to rename these columns something like drug_1, drug_2, ..., this would be easy to do with rename if there were just a few columns to rename. When there are more than just a few, individual renaming is somewhat tedious and error prone. We can use rename_with to do this in one operation. However, the code for doing so is not very simple and would require some proficiency in R and tidyverse. This function is essentially just a wrapper to a rename_with function to allow the renaming to be done in one simple command.

Examples

data_df <- readr::read_csv('
subject, age, gender, Aripiprazole, Clozapine, Olanzapine, Quetiapine
A, 27, F, 20, 10, 40, 25
B, 23, M, 21, 21, 35, 27
')
#> Rows: 2 Columns: 7
#> ── Column specification ────────────────────────────────────────────────────────
#> Delimiter: ","
#> chr (2): subject, gender
#> dbl (5): age, Aripiprazole, Clozapine, Olanzapine, Quetiapine
#> 
#>  Use `spec()` to retrieve the full column specification for this data.
#>  Specify the column types or set `show_col_types = FALSE` to quiet this message.

rename_with_seq(data_df, col_selector = Aripiprazole:Quetiapine, prefix = 'drug')
#> # A tibble: 2 × 7
#>   subject   age gender drug_1 drug_2 drug_3 drug_4
#>   <chr>   <dbl> <chr>   <dbl>  <dbl>  <dbl>  <dbl>
#> 1 A          27 F          20     10     40     25
#> 2 B          23 M          21     21     35     27