Use import
to import a list of data frames from a vector of file names or from a multi-object file (Excel workbook, .Rdata file, zip directory, or HTML file)
import_list( file, setclass, which, rbind = FALSE, rbind_label = "_file", rbind_fill = TRUE, ... )
file | A character string containing a single file name for a multi-object file (e.g., Excel workbook, zip directory, or HTML file), or a vector of file paths for multiple files to be imported. |
---|---|
setclass | An optional character vector specifying one or more classes to set on the import. By default, the return object is always a “data.frame”. Allowed values include “tbl_df”, “tbl”, or “tibble” (if using dplyr) or “data.table” (if using data.table). Other values are ignored, such that a data.frame is returned. |
which | If |
rbind | A logical indicating whether to pass the import list of data frames through |
rbind_label | If |
rbind_fill | If |
... | Additional arguments passed to |
If rbind=FALSE
(the default), a list of a data frames. Otherwise, that list is passed to rbindlist
with fill = TRUE
and returns a data frame object of class set by the setclass
argument; if this operation fails, the list is returned.
library('datasets') export(list(mtcars1 = mtcars[1:10,], mtcars2 = mtcars[11:20,], mtcars2 = mtcars[21:32,]), "mtcars.xlsx") # import a single file from multi-object workbook str(import("mtcars.xlsx", which = "mtcars1"))#> 'data.frame': 10 obs. of 11 variables: #> $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 #> $ cyl : num 6 6 4 6 8 6 8 4 4 6 #> $ disp: num 160 160 108 258 360 ... #> $ hp : num 110 110 93 110 175 105 245 62 95 123 #> $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 #> $ wt : num 2.62 2.88 2.32 3.21 3.44 ... #> $ qsec: num 16.5 17 18.6 19.4 17 ... #> $ vs : num 0 0 1 1 0 1 0 1 1 1 #> $ am : num 1 1 1 0 0 0 0 0 0 0 #> $ gear: num 4 4 4 3 3 3 3 4 4 4 #> $ carb: num 4 4 1 1 2 1 4 2 2 4#> List of 3 #> $ mtcars1 :'data.frame': 10 obs. of 11 variables: #> $ mtcars2 :'data.frame': 10 obs. of 11 variables: #> $ mtcars2.1:'data.frame': 12 obs. of 11 variables:# import and rbind all worksheets mtcars2 <- import_list("mtcars.xlsx", rbind = TRUE) all.equal(mtcars2, mtcars, check.attributes = FALSE)#> [1] "Length mismatch: comparison on first 11 components"# import multiple files export(mtcars, "mtcars.csv") export(mtcars, "iris.csv") str(import_list(dir(pattern = "csv$")), 1)#> List of 2 #> $ iris :'data.frame': 32 obs. of 11 variables: #> ..- attr(*, "filename")= chr "iris.csv" #> $ mtcars:'data.frame': 32 obs. of 11 variables: #> ..- attr(*, "filename")= chr "mtcars.csv"