[R] changing column labels for data frames inside a list

r-help at mmmmarascio.xyz r-help at mmmmarascio.xyz
Tue Mar 31 17:38:39 CEST 2015


> Date: Mon, 30 Mar 2015 09:54:39 -0400
> From: Vikram Chhatre <crypticlineage at gmail.com>
> To: r-help at r-project.org
> Subject: [R] changing column labels for data frames inside a list
> Message-ID:
>         <CAJZnH0=uGay_1VzjVTMMc=FweydKDJxm_TPi4hZO-ArDZTr1eQ at mail.gmai
> Content-Type: text/plain; charset="UTF-8"
>
> > summary(mygenfreqt)
>                   Length Class  Mode
> dat1.str 59220  -none- numeric
> dat2.str 59220  -none- numeric
> dat3.str 59220  -none- numeric
>
> > head(mylist[[1]])
>            1     2     3     4     5     6     7     8     9    10
>  12
> L0001.1 0.60 0.500 0.325 0.675 0.600 0.500 0.500 0.375 0.550 0.475 0.3
> 0.275
> L0001.2 0.40 0.500 0.675 0.325 0.400 0.500 0.500 0.625 0.450 0.525 0.6
> 0.725
>
> I want to change 1:12 to pop1:pop12
>
> mylist<- lapply(mylist, function(e) colnames(e) <- paste0('pop',1:12))
>
> What this is doing is replacing the data frames with just names
> pop1:pop12.  I just want to replace the column labels.
>
> Thanks for any suggestions.

Some readers have already replied, but here is another option that exploits lapply()'s "..." parameter.  First, we make a reproducible example.

(lista <- list(mtcars, mtcars))

Now, we get the unique number of columns of the data frames in the variable "lista".

(n.cols <- unique(sapply(lista, ncol)))

Finally, we call lapply() and `colnames<-` to change the column names of both data frames in "lista".  See lapply()'s "..." parameter (?lapply).

(lista <- lapply(X = lista, FUN = `colnames<-`, paste0("pop", seq_len(n.cols))))

>         [[alternative HTML version deleted]]



More information about the R-help mailing list