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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With