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
2 Answers 2
Most R functions are vectorized, you don't need the for
loop:
colRename <- function(x) {
setNames(x, paste0("column", seq_len(ncol(x))))
}
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.
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\$,
and around=
as well as<-
. Improves readability. More if interested: google.github.io/styleguide/Rguide.xml \$\endgroup\$