Reputation: 115
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!
Upvotes: 0
Views: 1004
Reputation: 389055
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)
}
Upvotes: 1