user2568648
user2568648

Reputation: 3181

R change column names over multiple data

I'm trying to change column names over multiple data sets. I have tried writing the following function to do this:

# simplified test data #
df1<-as.data.frame(c("M","F"))
colnames(df1)<-"M1"

# my function #
rename_cols<-function(df){
  colnames(df)[names(df) == "M1"] <- "sex"
}
rename_cols(df1)

However when testing this function on df1, the column is always called "M1" instead of "sex". How can I correct this?

SOLUTION - THANKS TO DAVID ARENBERG

rename_cols<-function(df){
  colnames(df)[names(df) == "M1"] <- "sex"
  df
}
df1<-rename_cols(df1)

Upvotes: 0

Views: 1040

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

Here is another solution which gets around the problem of functions operating in a temporary space:

df <- as.data.frame(c("M","F"))
colnames(df) <- "M1"

rename_cols <- function(df) {
    colnames(df)[names(df) == "M1"] <<- "sex"
}

> rename_cols(df)         # this will operate directly on the 'df' object
> df
  sex
1   M
2   F

Using the global assignment operator <<- makes the name changes to the input data frame df "stick". Granted, this solution is not ideal because it means the function could potentially do something unwanted. But I feel this is in the spirit of what you were trying to do originally.

Upvotes: 1

Related Questions