1
\$\begingroup\$

I wrote this simple function to rename columns in a data frame to standardized names in R. This function is useful when we have a very large data set with large number of columns especially for machine learning applications.

colRename<-function(x){  
  for(i in 1:ncol(x)){
    colnames(x)[i] <- paste("column",i,sep="")
  }  
  return(x)
}

An example

library(quantmod)

colRename<-function(x){  
  for(i in 1:ncol(x)){
    colnames(x)[i] <- paste("column",i,sep="")
  }  
  return(x)
}

aapl=getSymbols("AAPL",from="2015-01-01",auto.assign=F)
head(colRename(aapl))

Result

           column1 column2 column3 column4  column5  column6
2015-01-02  111.39  111.44  107.35  109.33 53204600 105.6986
2015-01-05  108.29  108.65  105.41  106.25 64285500 102.7209
2015-01-06  106.54  107.43  104.63  106.26 65797100 102.7306
2015-01-07  107.20  108.20  106.70  107.75 40105900 104.1711
2015-01-08  109.23  112.15  108.70  111.89 59364500 108.1736
2015-01-09  112.67  113.25  110.21  112.01 53699500 108.2896
\$\endgroup\$
  • 1
    \$\begingroup\$ If your data is very large, you should consider not writing a function as it will temporarily duplicate your data, which is unnecessarily slow and memory-expensive. Instead, you can just do names(x) <- paste0("column", seq_len(ncol(x))) which will only modify the names attributes of your object and not reassign the data in memory. \$\endgroup\$ – flodel Aug 16 '16 at 22:28
  • \$\begingroup\$ A friendly tip: I suggest using spaces after , and around = as well as <-. Improves readability. More if interested: google.github.io/styleguide/Rguide.xml \$\endgroup\$ – snoram Aug 21 '16 at 17:12
5
\$\begingroup\$

Most R functions are vectorized, you don't need the for loop:

colRename <- function(x) {
   setNames(x, paste0("column", seq_len(ncol(x))))
}
\$\endgroup\$
2
\$\begingroup\$

Sorry, I can't replicate your example because I couldn't install the package via the Online Compiler but I don't think you need a function or a for loop. For instance If I have a 2 X 3 data.frame called dat with three columns as shown below

dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))

dat
x y z
1 1 3 5
2 2 4 6

names(dat)<-paste0("column", 1:ncol(dat))
column1 column2 column3                                                                                                                                     
1       1       3       5                                                                                                                                     
2       2       4       6  

I hope this helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.