加载包

library(tidyverse)
## -- Attaching packages ---- tidyverse 1.3.0 --
## √ ggplot2 3.3.0     √ purrr   0.3.3
## √ tibble  2.1.3     √ dplyr   0.8.5
## √ tidyr   1.0.2     √ stringr 1.4.0
## √ readr   1.3.1     √ forcats 0.5.0
## -- Conflicts ------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(purrr)
library(readxl)
library(here)
## here() starts at D:/RBookLearning/Data-Science-and-Economics
library(writexl)
library(furrr)
## Loading required package: future
library(tictoc)

生成100个Excel文件

data <- tibble(x = 1:60,
               y = 2 + x + rnorm(60))

data %>% 
  ggplot(aes(x,y)) +
  geom_point() +
  geom_smooth(method = "lm")
## `geom_smooth()` using formula 'y ~ x'

x = 1:10
map(x,function(x){
  return(x)
})->df
df   # 最终形成一个列表
## [[1]]
## [1] 1
## 
## [[2]]
## [1] 2
## 
## [[3]]
## [1] 3
## 
## [[4]]
## [1] 4
## 
## [[5]]
## [1] 5
## 
## [[6]]
## [1] 6
## 
## [[7]]
## [1] 7
## 
## [[8]]
## [1] 8
## 
## [[9]]
## [1] 9
## 
## [[10]]
## [1] 10
df %>% bind_cols()
## # A tibble: 1 x 10
##      V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
##   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
## 1     1     2     3     4     5     6     7     8     9    10
x <- as.character(1:100)
x
##   [1] "1"   "2"   "3"   "4"   "5"   "6"   "7"   "8"   "9"   "10"  "11"  "12" 
##  [13] "13"  "14"  "15"  "16"  "17"  "18"  "19"  "20"  "21"  "22"  "23"  "24" 
##  [25] "25"  "26"  "27"  "28"  "29"  "30"  "31"  "32"  "33"  "34"  "35"  "36" 
##  [37] "37"  "38"  "39"  "40"  "41"  "42"  "43"  "44"  "45"  "46"  "47"  "48" 
##  [49] "49"  "50"  "51"  "52"  "53"  "54"  "55"  "56"  "57"  "58"  "59"  "60" 
##  [61] "61"  "62"  "63"  "64"  "65"  "66"  "67"  "68"  "69"  "70"  "71"  "72" 
##  [73] "73"  "74"  "75"  "76"  "77"  "78"  "79"  "80"  "81"  "82"  "83"  "84" 
##  [85] "85"  "86"  "87"  "88"  "89"  "90"  "91"  "92"  "93"  "94"  "95"  "96" 
##  [97] "97"  "98"  "99"  "100"
tic()
map(x,function(x){
  write_xlsx(data,path = str_c(here::here(),"/R高级编程","/data/",x,".xlsx"))
})
toc()

读取100个Excel文件

x <- as.character(1:100)

tic()
map(x,function(x){
  data <- read_excel(str_c(here::here(),"/R高级编程/data/",x,".xlsx"))
  return(data)
})->df
toc()
## 1.36 sec elapsed

Great!!!

合并数据

df %>% 
  bind_rows() %>% 
  datatable()

\[ y = 2 + x + rnorm(60) \]

df %>% 
  bind_rows() %>% 
  group_by(x) %>% 
  summarise(mean_y = mean(y))->df1

df1 %>% 
  ggplot(aes(x,mean_y)) +
  geom_point() +
  geom_smooth(method = "lm")
## `geom_smooth()` using formula 'y ~ x'