3

I have a snipet of code that reads all the files with a specific extension from a folder and each dataset is saved as a data frame with default name. The code was working fine untill I turned it into a function. The function runs fine but is not returning anything. I wanted to ask if there is a way of having this function return all the data frames?

The function is below:

library(devtools); install_github(BioStatMatt/sas7bdat.parso)

ReadFiles <- function()
  {
  path <- "C:/Users/abc/Desktop/abc/test/"
  files <- list.files(path=path, pattern="*.sas7bdat")
    for(file in files)
      {
        perpos <- which(strsplit(file, "")[[1]]==".")
        assign(
        gsub(" ","",substr(file, 1, perpos-1)), 
        read.sas7bdat.parso(paste(path,file,sep="")))
      }
  }

I will appreciate some guidance onto how I can make this function work.

Thanks.

1
  • Instead of calling the assign function, couldn't you put the data frames in a vector and return that from the function? Currently looking at the code I don't see a return statement at the end of the function.
    – ColinMc
    Jul 6, 2015 at 1:06

1 Answer 1

6

Your function is indeed not returning anything. To resolve this, you could save the dataframes that you generate inside the for loop in a list and then return this resultlist with all the dataframes in it.

Conceptually, it will look something like this:

ReadFiles <- function()
{
  files <- # fetch the files
  resultList <- vector("list",length(files))
  for(i in seq(1,length(files))) # process each file
  {
    file <- files[i]
    resultList[[i]] <- # fetch your data(frame)
  }
  resultList # Return the result!
}

results <- readFiles()
# You can now access your individual dataframes like this:
dataFrame1 <- results[[1]]
# Or merge them all together if you like:
combinedDataFrame <- do.call("rbind",results)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.