Skip to content
Prev 138403 / 398506 Next

looping through data frames in a workspace

lucy b wrote:
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