用`purrr`包批量读取xlsx数据并转化为一个数据框

偶然间看到了Colin Fay在某404网站上PO出的一条推特信息,上面记录用purrr包迅速便捷读取某一文件夹下多个csv文件并转化为一个数据框的代码,特此记之。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
library(purrr)
path <- "C:\\Users\\Lenovo\\Documents\\R_package_learning\\purrr"
# 不加ID标识符
files_names <- list.files(path = path,
pattern = "\\.xlsx")
files_names
#> [1] "iris1.xlsx" "iris2.xlsx" "iris3.xlsx"
all_files <- map_df(paste0(path, "\\", files_names), readxl::read_xlsx)
all_files
#> # A tibble: 450 x 5
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <dbl> <dbl> <dbl> <dbl> <chr>
#> 1 5.10 3.50 1.40 0.200 setosa
#> 2 4.90 3.00 1.40 0.200 setosa
#> 3 4.70 3.20 1.30 0.200 setosa
#> 4 4.60 3.10 1.50 0.200 setosa
#> 5 5.00 3.60 1.40 0.200 setosa
#> 6 5.40 3.90 1.70 0.400 setosa
#> 7 4.60 3.40 1.40 0.300 setosa
#> 8 5.00 3.40 1.50 0.200 setosa
#> 9 4.40 2.90 1.40 0.200 setosa
#> 10 4.90 3.10 1.50 0.100 setosa
#> # ... with 440 more rows
# 加上ID标志符
list.files(path = path,
pattern = "\\.xlsx", full.names = TRUE) %>%
set_names(basename(.)) %>%
print() %>%
map_df(readxl::read_xlsx, .id = "file")
#> iris1.xlsx
#> "C:\\Users\\Lenovo\\Documents\\R_package_learning\\purrr/iris1.xlsx"
#> iris2.xlsx
#> "C:\\Users\\Lenovo\\Documents\\R_package_learning\\purrr/iris2.xlsx"
#> iris3.xlsx
#> "C:\\Users\\Lenovo\\Documents\\R_package_learning\\purrr/iris3.xlsx"
#> # A tibble: 450 x 6
#> file Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <chr> <dbl> <dbl> <dbl> <dbl> <chr>
#> 1 iris1.xlsx 5.10 3.50 1.40 0.200 setosa
#> 2 iris1.xlsx 4.90 3.00 1.40 0.200 setosa
#> 3 iris1.xlsx 4.70 3.20 1.30 0.200 setosa
#> 4 iris1.xlsx 4.60 3.10 1.50 0.200 setosa
#> 5 iris1.xlsx 5.00 3.60 1.40 0.200 setosa
#> 6 iris1.xlsx 5.40 3.90 1.70 0.400 setosa
#> 7 iris1.xlsx 4.60 3.40 1.40 0.300 setosa
#> 8 iris1.xlsx 5.00 3.40 1.50 0.200 setosa
#> 9 iris1.xlsx 4.40 2.90 1.40 0.200 setosa
#> 10 iris1.xlsx 4.90 3.10 1.50 0.100 setosa
#> # ... with 440 more rows

参考