importAll | R Documentation |
Imports multiple files into a list, concatenates them into a single table, and adds an 'fName' variable.
The files can be selected either by giving a file list (character vector), or by specifying a pattern.
importAll(
path = ".",
pattern = "",
ignore.case = FALSE,
importFunction = NULL,
fill = FALSE,
fileList = NULL
)
path |
Path to the directory, passed to 'list.files'. |
pattern |
Pattern to match file names, passed to 'list.files'. |
ignore.case |
Logical. If 'TRUE', ignores case when matching file names. Passed to 'list.files'. Default behavior is case-sensitive ('FALSE') |
importFunction |
A custom function for importing files. If not set, the function selects an import method based on the file extension. |
fill |
Logical. Passed to 'rbind' to allow filling missing columns. |
fileList |
A character vector of file names to import (used instead of 'pattern'). |
A data frame containing the concatenated table with the fName column
# Directory containing test files
test_path <- tempdir()
# Create test files
write.csv( data.frame(a = 1:3, b = 4:6) , file.path(test_path, "file1.csv"))
write.csv( data.frame(a = 7:9, b = 10:12) , file.path(test_path, "file2.csv"))
write.csv( data.frame(a = 3:5, b = 8:10) , file.path(test_path, "file3.csv"))
saveRDS( data.frame(a = 1:5, b = 6:10) , file.path(test_path, "file1.rds"))
saveRDS( data.frame(a = 11:15, b = 16:20), file.path(test_path, "file2.rds"))
# Example 1 : Import all csv files
result <- importAll(path = test_path, pattern = "\\.csv$")
print(result)
# Example 2: Import only selected files
file_list <- c("file1.csv", "file2.csv")
result <- importAll(path = test_path, fileList = file_list)
print(result)
# Example 3: Import all .rds files
result <- importAll(path = test_path, pattern = "\\.rds$")
print(result)
# Example 4: Use a custom import function
custom_import <- function(file) {
data <- read.csv(file, stringsAsFactors = FALSE)
return(data)
}
result <- importAll(path = test_path, pattern = "\\.csv$", importFunction = custom_import)
print(result)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.