获取使用 purrr::map 创建的列表项的名称

Get the name of a list item created with purrr::map

我用 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

根据@Spacedman

的建议编辑

我还需要在 process_csv_data 函数中分别处理每个 tibble/data 帧。

purrr::map(all_csv, process_csv_data)

如何在没有for循环的情况下获取大列表中单个项目的名称?

使用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

函数中作为 x 的列表的输出被 message 修改了一点,但它是 L 的列表元素。

您可以利用 purrr 将所有数据保存在一个嵌套的 tibble 中。这样每个 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)