I am writing a ggplot wrapper to create multiple graphs based on different data sets. When I pass the names of the columns to the function, I need to rename the column names so that ggplot can understand the link.
However, I struggle with renaming data frame columns
here is the data frame:
df <- data.frame(col1=1:3,col2=3:5,col3=6:8)
here are my column names to search for:
col1_search <- "col1"
col2_search <- "col2"
col3_search <- "col3"
and here are the column names to replace:
col1_replace <- "new_col1"
col2_replace <- "new_col2"
col3_replace <- "new_col3"
when I search for column names, R sorts the column indices and ignores the search location.
for example, when I run the following code, I expected the new headers to be new_col1, new_col2 and new_col3, instead of them there will be the names of the new columns: new_col3, new_col2 and new_col1
colnames(df)[names(df) %in% c(col3_search,col2_search,col1_search)] <- c(col3_replace,col2_replace,col1_replace)
Does anyone have a solution where I can search for column names and replace them in that order?
source
share