2
votes

I'm working from this answer trying to optimize the second argument in the plyr:rename, as suggested by Jared.

In short they are renaming some columns in a data frame using plyr like this,

df <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df
newNames <- c("new_col1", "new_col2", "new_col3")
oldNames <- names(df)

require(plyr)
df <- rename(df, c("col1"="new_col1", "col2"="new_col2", "col3"="new_col3"))
df

In passing Jared writes '[a]nd you can be creative in making that second argument to rename so that it is not so manual.'

I've tried being creative like this,

df <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df
secondArgument <- paste0('"', oldNames, '"','=', '"',newNames, '"',collapse = ',')
df <- rename(df, secondArgument)
df

But it does not work, can anyone help me automates this?

Thanks!

Update Sun Sep 9 11:55:42PM

I realized I should have been more specific in my question.

I'm using plyr::rename because I, in my real life example, have other variables and I don't always know the position of the variables I want to rename. I'll add an update to my question

My case look like this, but with 100+ variables

df2 <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df2
df2 <- rename(df2, c("col1"="new_col1", "col3"="new_col3"))
df2

df2 <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df2
newNames <- c("new_col1", "new_col3")
oldNames <- names(df[,c('col1', 'col3')])
secondArgument <- paste0('"', oldNames, '"','=', '"',newNames, '"',collapse = ',')
df2 <- rename(df2, secondArgument)
df2

Please add an comment if there is anything I need to clarify.

3

3 Answers

3
votes

Solution to modified question:

df2 <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df2
newNames <- c("new_col1", "new_col3")
oldNames <- names(df2[,c('col1', 'col3')]) 

(Isn't oldNames equal toc('col1','col3') by definition?)

Solution with plyr:

secondArgument <- setNames(newNames,oldNames)
library(plyr)
df2 <- rename(df2, secondArgument)
df2

Or in base R you could do:

names(df2)[match(oldNames,names(df2))] <- newNames
3
votes

Set the names on newNames to the names from oldNames:

R> names(newNames) <- oldNames
R> newNames
      col1       col2       col3 
"new_col1" "new_col2" "new_col3" 
R> df <- rename(df, newNames)
R> df
  new_col1 new_col2 new_col3
1        1        3        6
2        2        4        7
3        3        5        8
2
votes

plyr::rename requires a named character vector, with new names as values, and old names as names.

This should work:

names(newNames) <- oldNames
df <- rename(df, newNames)
df
  new_col1 new_col2 new_col3
1        1        3        6
2        2        4        7
3        3        5        8