我用purrr :: map检索了一个csv文件列表,得到了一个大的列表.
csv_files <- list.files(path = data_path, pattern = '\\.csv$', full.names = TRUE)
all_csv <- purrr::map(csv_files, readr::read_csv2)
names(all_csv) <- gsub(data_path, "", csv_files)
return all_csv
Run Code Online (Sandbox Code Playgroud)
按照@Spacedman的建议编辑
我还需要在process_csv_data函数中单独处理每个tibble /数据帧.
purrr::map(all_csv, process_csv_data)
Run Code Online (Sandbox Code Playgroud)
如何在没有for循环的情况下检索大型列表中单个项目的名称?
Spa*_*man 10
使用map2,如在此可重现的示例中:
> L = list(a=1:10, b=1:5, c=1:6)
> map2(L, names(L), function(x,y){message("x is ",x," y is ",y)})
x is 12345678910 y is a
x is 12345 y is b
x is 123456 y is c
Run Code Online (Sandbox Code Playgroud)
x函数中列表的输出有点受到影响message,但是它的列表元素L.
您可以利用purrr将所有数据保留在一个嵌套的小块中。这样,每个csv和已处理的csv都将直接与相应的csv名称链接:
csv_files <- list.files(path = data_path, pattern = '\\.csv$', full.names = TRUE)
all_csv <- tibble(csv_files) %>%
mutate(data = map(csv_files, read_csv2),
processed = map(data, process_csv_data),
csv_files = gsub(data_path, "", csv_files)) %>%
select(-data)
Run Code Online (Sandbox Code Playgroud)