2
\$\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
asked Aug 16, 2016 at 13:54
\$\endgroup\$
2
  • 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\$ Commented Aug 16, 2016 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\$ Commented Aug 21, 2016 at 17:12

2 Answers 2

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))))
}
answered Aug 16, 2016 at 15:34
\$\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.

answered Aug 16, 2016 at 16:37
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.