用`purrr`包批量读取xlsx数据并转化为一个数据框 发表于 2018-01-06 偶然间看到了Colin Fay在某404网站上PO出的一条推特信息,上面记录用purrr包迅速便捷读取某一文件夹下多个csv文件并转化为一个数据框的代码,特此记之。 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152library(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 参考 df a list