Friday, December 17, 2010

Generate a series of column names in R

#if you want a series of column names, e.g., col1,col2,col3, ...,
#you can use:
mydf<-data.frame(matrix(ncol=5,nrow=4))
colnames(mydf)<-c("col1","col2","col3","col4","col5")
#Well, it does work, but how about for 50 columns?
#A loop! Sounds great. Okay,
mydf<-data.frame(matrix(ncol=50,nrow=4))
for (n in 1:ncol(mydf))
{
      colnames(mydf)[n]<-paste("col",n,sep="")
}
#But again, it's as urgly as the textbook. Here we offer a much better solution:
colnames(mydf)<-paste(rep("col",ncol(mydf)),c(1:ncol(mydf)),sep="")
#Smart, eh? At least the nicer looking :)
#From http://scriptdemo.blogspot.com

4 comments:

Unknown said...

Very helpful, non-ugly, method. Thanks.

Allan said...

I need to name the first columm whith another name like (Time, host1, host2, host3). Can u help me?

Louis said...

Bit late @allan but this has worked for me:

colnames(df)<-c("a","b","c","d", paste(rep("tag",(ncol(df)-4)),c(1:(ncol(df)-4)),sep=""))

Where 4 refers to the number of columns whose name you manually specify

Nikki said...

Louis' solution worked for me

ShowCalendar