0

I'm having trouble reading several data files at once. If I want someone to plug in their file directory and have the function read all the files in it, how would I go about it?

I have a folder with 15 files that need to be read. So doing this manually was fine until I decided to use the lapply function - I don't want to use a loop. Here was my code:

files <- list.files(path = "/User/Zoe/Documents etc.....", pattern = ".csv")
all_df <- lapply(files, read.table(file, header = TRUE, fill = TRUE, skip = 1)). 

An error shows up saying : 'file' must be a character string or connection. I'm guessing when I use the parameter "files" in lapply it is not the correct type of variable?

Then lastly, how would I be able to create a function of the above (assuming it worked)? I'd go about it like this:

read_all_data <- function(folder_name, dir) {
 files <- list.files(dir, pattern = ".csv")
 all_df <- lapply(files, read.table(file, header = TRUE, fill = TRUE, skip = 1)). 
}

Thanks for the help! The actual reading all files is more important to me than the function!

1 Answer 1

1

You have slight syntax error. Either use this :

read_all_data <- function(dir) {
  files <- list.files(dir, pattern = ".csv", full.names = TRUE)
  all_df <- lapply(files, read.table, header = TRUE, fill = TRUE, skip = 1)
  return(all_df)
}

Or with an anonymous function.

read_all_data <- function(dir) {
  files <- list.files(dir, pattern = ".csv", full.names = TRUE)
  all_df <- lapply(files, function(x) 
                   read.table(x, header = TRUE, fill = TRUE, skip = 1))
  return(all_df)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank-you, the syntax compiled however when I use the function and plug in read_all_data("my path etc ") is just returns : list().
Can you share the exact command that you ran?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.