Re: [R] looping through data frames in a workspace

From: Richard Cotton <Richard.Cotton_at_hsl.gov.uk>
Date: Tue, 04 Mar 2008 01:48:26 -0800 (PST)

lucy b wrote:
>
> I have a workspace containing only data frame objects. I would like to
> loop though each one and clean-up text columns in them. How can I have
> R loop through the list? I have tried to find an answer in R help but
> the closest solution I can find is to make a static list of data
> frames, as illustrated in this recent post:
> ...
> I would like to avoid having to type-out a very long list over and
> over again. I have tried every variation I could think of similar to:
>
> for(df in list(noquote(ls()))) {
>
> do stuff with df
>
> }
>

If you name your data frames consistently (e.g. df1, df2, df3 etc.), then you can access them using mget:

df1 <- data.frame(a=runif(10), b=letters[1:10])
df2 <- data.frame(c=rnorm(5))
df3 <- data.frame(11:20)

dataframes <- mget(paste("df", 1:3, sep=""), envir=.GlobalEnv)

Alternatively, if you want every dataframe in your workspace, try: vars <- ls()
nvars <- length(vars)
dataframes <-list()
j <- 1
for(i in 1:nvars)
  {
    if(class(get(vars[i]))=="data.frame")

      {
        dataframes[[j]] <- get(vars[i])
        names(dataframes)[j] <- vars[i]
        j <- j+1
      }

  }

Regards,
Richie.

Mathematical Sciences Unit
HSL

-- 
View this message in context: http://www.nabble.com/looping-through-data-frames-in-a-workspace-tp15815971p15823720.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.
Received on Tue 04 Mar 2008 - 09:52:01 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 04 Mar 2008 - 10:30:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive