To rename column names in a data frame in R using dplyr, we can use the rename_with()
function along with the starts_with()
function to target specific column names based on a prefix. Here's an example:
main.r347 chars12 lines
In this example, we first created a sample data frame called df
. Next, we used rename_with()
to add a prefix of "new_" to any columns that start with "var1" or "var2". The ~paste0("new_", .)
syntax is what adds the prefix to the selected column names. We then assigned the result to df_renamed
and printed the resulting data frame.
The resulting output should look like this:
main.r307 chars7 lines
Here, we can see that the original column names starting with "var1" and "var2" have been renamed with the "new_" prefix using dplyr.
gistlibby LogSnag