写多个文件
# 1.0 LIBRARIES ----
library(tidyverse)
library(fs)
# 2.0 READING MULTIPLE CSV ----
# - Tip 001 - Revised to specify column types
# - FIXES Error: Can't combine `drv` <character> and `drv` <logical>.
directory_that_holds_files <- "001_read_multiple_files/data/"
car_data_list <- directory_that_holds_files %>%
dir_ls() %>%
map(
.f = function(path) {
read_csv(
path,
col_types = cols(
manufacturer = col_character(),
model = col_character(),
displ = col_double(),
year = col_double(),
cyl = col_double(),
trans = col_character(),
drv = col_character(),
cty = col_double(),
hwy = col_double(),
fl = col_character(),
class = col_character()
)
)
}
)
# 3.0 BINDING DATA FRAMES ----
# - bind_rows() : Taught in DS4B 101-R
car_data_tbl <- car_data_list %>%
set_names(dir_ls(directory_that_holds_files)) %>%
bind_rows(.id = "file_path")
car_data_tbl
# 4.0 CREATE A DIRECTORY ----
# - fs package
new_directory <- "004_writing_multiple_files/car_data_01/"
dir_create(new_directory)
# 5.0 SPLITTING & WRITING CSV FILES ----
# - Text (stringr): Taught in DS4B 101-R
# - Iteration (purrr map): Taught in DS4B 101-R
car_data_tbl %>%
mutate(file_path = file_path %>% str_replace(directory_that_holds_files, new_directory)) %>%
group_by(file_path) %>%
group_split() %>%
map(
.f = function(data) {
write_csv(data, path = unique(data$file_path))
}
)
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
53
54
55
56
57
58
59
60
61
62
63
64
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
53
54
55
56
57
58
59
60
61
62
63
64
编辑 (opens new window)
上次更新: 2021/06/24, 13:39:01