Store multiple data frames and return them from a function
I have a snipet of code that reads all files with a specific extension from a folder and each dataset is saved as a dataframe with a default name. The code worked fine until I turned it into a function. The function works fine but returns nothing. I wanted to ask if there is a way to return this function to all data frames?
Function 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'll take care of some guidelines on how I can get this feature to work.
Thank.
+3
source to share
1 answer
Your function doesn't really return anything. To solve this problem, you can store the data you create in the for loop in a list and then return that list of results with all the data 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)
+6
source to share