[R] rename and concatenate name of columns
Ista Zahn
istazahn at gmail.com
Fri Jun 14 16:07:04 CEST 2013
On Fri, Jun 14, 2013 at 10:01 AM, arun <smartpink111 at yahoo.com> wrote:
> Hi,
> rename_columns<- function(dat){
> for(i in 2:(ncol(dat))){
> names(dat)[i]<- paste(names(dat)[1],names(dat)[i],sep="_")
>
> }
> dat
> }
Or even better, get rid of the unnecessary loop:
rename_columns <- function(DF) {
names(DF) <- c(names(DF)[1], paste(names(DF)[1], names(DF)[-1], sep="_"))
return(DF)
}
Best,
Ista
>
> dat1<- read.table(text="
> chr pos ref alt
> chr1 5 A G
> chr1 8 T C
> chr2 2 C T
> ",sep="",header=TRUE,stringsAsFactors=FALSE)
>
>
> rename_columns(dat1)
> # chr chr_pos chr_ref chr_alt
> #1 chr1 5 A G
> #2 chr1 8 T C
> #3 chr2 2 C T
> A.K.
>
>
>
> ----- Original Message -----
> From: Arman Eshaghi <arman.eshaghi at gmail.com>
> To: r-help at r-project.org
> Cc:
> Sent: Friday, June 14, 2013 9:34 AM
> Subject: [R] rename and concatenate name of columns
>
> Dear all,
>
> I have different data frames for which I would like to modify names of each
> column such that the new name would include the name of the first column
> added to the name of other columns; I came up with the following code.
> Nothing changes when I run the following code. I would be grateful if
> someone could help me.
>
> All the best,
> -Arman
>
> rename_columns <- function(dataset) {
> for (i in 2:(ncol(dataset))) {names(dataset)[i] <- paste(names(dataset)[1],
> names(dataset)[i], sep="_")
> }
> }
>
> rename_columns(dataset) %nothing happens!
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list