[R] Putting column names in some automated way

Bernd Weiss bernd.weiss at uni-koeln.de
Sun Sep 16 11:01:17 CEST 2007


Megh Dal schrieb:
> Dear all,
> 
> I have following codes:
> 
> colnames(data) = c("var", "var", "var")
> i = c(1,2,3)
> 
> Now I want construct a "for" loop starting from 1 to 3 to give the new names of columns for dataframe "data" like below
> 
> colnames(data) 
>> c("var1", "var2", "var3")
> 
> Definitely I could do this manually, however I want to put this in a automated way so that I can do this for any number of columns.
> 

x <- data.frame(c(1,2),c(3,4),c(5,6))
colnames(x) <- rep("var",3)
colnames(x) <- paste(colnames(x),1:dim(x)[2],sep = "")


## Maybe, you want your own very simple function for renaming
## a data frame...
myRename <- function(df){
	colnames(df) <- paste(colnames(df),1:dim(df)[2],sep = "")
	return(df)
}

x <- data.frame(c(1,2), c(3,4), c(5,6), c(5,6), c(5,6))
colnames(x) <- rep("var",5)
myRename(x)


HTH,

Bernd



More information about the R-help mailing list