Rename columns of a data frame by searching for a column name

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?

+5
source share
4
require(plyr)
df <- data.frame(col2=1:3,col1=3:5,col3=6:8)
df <- rename(df, c("col1"="new_col1", "col2"="new_col2", "col3"="new_col3"))
df

rename, .

+8
> names(df)[grep("^col", names(df))] <- 
                        paste("new", names(df)[grep("^col", names(df))], sep="_")
> names(df)
[1] "new_col1" "new_col2" "new_col3"

, :

names(df)[sapply(oldNames, grep, names(df) )] <- newNames

sapply() - ed grep newNames. , , , .

+4

hmm, this can be tricky, but the first thing that comes to my mind:

lookup <- data.frame(search = c(col3_search,col2_search,col1_search),
                     replace = c(col3_replace,col2_replace,col1_replace))

colnames(df) <- lookup$replace[match(lookup$search, colnames(df))]
+2
source

Second sentence @justin aes_string. But for future renaming you can try.

require(stringr)
df <- data.frame(col1=1:3,col2=3:5,col3=6:8)
oldNames <- c("col1", "col2", "col3")
newNames <- c("new_col1", "new_col2", "new_col3")
names(df) <- str_replace(string=names(df), pattern=oldNames, replacement=newNames)
+1
source

All Articles