How can I export a csv file for each element of a list and name the files according to matching values of another dataset?

Viewed 41

I have a codelist with hundreds of Diseases, and multiple codes for each Disease. I need to save one individual codelist for each Disease and name it after a specific codelist name.

I created a large vector of lists for each Disease using the command below:

Disease <- as.character(c("HIV","HIV", "HIV", "HIV", "anaemia", "anaemia", "anaemia", "Chronic Kidney Disease", "Chronic Kidney Disease"))
Code <- c(123, 432, 567, 876, 433, 096, 543, 912, 456)
codelist <- data.frame(Disease, Code)
codelist
                 Disease Code
1                    HIV  123
2                    HIV  432
3                    HIV  567
4                    HIV  876
5                anaemia  433
6                anaemia   96
7                anaemia  543
8 Chronic Kidney Disease  912
9 Chronic Kidney Disease  456

    list <- codelist %>%
      dplyr::group_split(Disease)

This give me one list for each Disease:

> list
<list_of<
  tbl_df<
    Disease: character
    Code   : double
  >
>[3]>
[[1]]
# A tibble: 3 × 2
  Disease  Code
  <chr>   <dbl>
1 anaemia   433
2 anaemia    96
3 anaemia   543

[[2]]
# A tibble: 2 × 2
  Disease                 Code
  <chr>                  <dbl>
1 Chronic Kidney Disease   912
2 Chronic Kidney Disease   456

[[3]]
# A tibble: 4 × 2
  Disease  Code
  <chr>   <dbl>
1 HIV       123
2 HIV       432
3 HIV       567
4 HIV       876

Also, I have a df with the names for each codelist according to the Disease:

Disease <- as.character(c("anaemia", "Chronic Kidney Disease", "HIV"))
File_name <- c("ICD_anemia_2010", "ICD_CKD_2022", "ICD_HIV_2010")
Codelists_names <- data.frame(Disease, File_name)
Codelists_names
                 Disease       File_name
1                anaemia ICD_anemia_2010
2 Chronic Kidney Disease    ICD_CKD_2022
3                    HIV    ICD_HIV_2010

I would like to export an individual csv file for each Disease naming each file according to the column File_name from Codelists_names that matches that specific Disease.

How could I do that, please? Many thanks.

1 Answers

Basically two steps here:

  1. Merge in your filenames using dplyr::left_join(), then base::split() by File_name. This will give you a named list of dataframes, where each name is the filename to be saved to.
  2. Use purrr::iwalk() to iterate over the list, saving each dataframe to the path specified in its name.
library(tidyverse)

codelist %>% 
  left_join(Codelists_names, by = "Disease") %>% 
  split(.$File_name) %>% 
  map(~ select(.x, !File_name)) %>% 
  iwalk(~ write_csv(.x, str_c(.y, ".csv")))

# check results
list.files(pattern = "csv")
# "ICD_anemia_2010.csv" "ICD_CKD_2022.csv"    "ICD_HIV_2010.csv"

read_csv("ICD_HIV_2010.csv")
# # A tibble: 4 x 2
#   Disease  Code
#   <chr>   <dbl>
# 1 HIV       123
# 2 HIV       432
# 3 HIV       567
# 4 HIV       876
Related