[R] accessing names of lists in a list

Greg Snow Greg.Snow at imail.org
Wed Jul 6 22:20:21 CEST 2011

In general, if the data frames are all related then it is best to keep them together in a list like you have.  But if you want to change the names of the component data frames then you can use a loop, or sometimes better use the lapply function.  Here is a basic example:

tmp <- list( df1=data.frame(x=1:10, y=rnorm(10)), 
 df2=data.frame(x=1:100, y=rnorm(100)),
 df3=data.frame(x=1:1000, y=rnorm(1000)))


tmp <- lapply( tmp, function(x){ names(x)[1] <- 'xx';x})


Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of tomtomme
> Sent: Wednesday, July 06, 2011 1:24 PM
> To: r-help at r-project.org
> Subject: [R] accessing names of lists in a list
> After importing multiple files to data.frames in R, I want to rename
> all
> their columns and do other operations with them. The data.frame names
> are
> not continuous like 1, 3, 4, 6.
> I could not find a way of creating a list of the data.frames and loop
> this
> and ended up putting them into a list first:
> # get all objects
> all.obj = sapply(ls(), get)
> # get data frames
> dfrs = all.obj[sapply(all.obj, is.data.frame)]
> but then I get lists within lists:
> structure(list(`1` = structure(list(Datum = structure(c(...
> my problem now is how to access the inner list, for example to rename
> the
> "Datum" to "date". The following changes only the outer list:
> names(dfrs) <- c("date", "time", "temp","")
> with the result:
> structure(list(date = structure(list(Datum = structure(c(...
> Or isn´t there a way to avoid the list and just loop through the
> data.frames
> of your workspace regardless of number and naming of the data.frames
> and
> thus apply different operations on them like the renaming of the
> columns?
> Many thanks!
> --
> View this message in context: http://r.789695.n4.nabble.com/accessing-
> names-of-lists-in-a-list-tp3649750p3649750.html
> Sent from the R help mailing list archive at Nabble.com.
> ______________________________________________
> 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