IAMconsortium / common-definitions

Repository for definitions and mappings in model comparison projects
Creative Commons Zero v1.0 Universal
9 stars 18 forks source link

R functions converting dataframe/spreadsheet to yaml files #63

Closed realxinzhao closed 3 months ago

realxinzhao commented 4 months ago

@danielhuppmann @FlorianLeblancDr @flohump

I wrote a function to convert dataframe in r to yaml files. Please spread the word, in case useful.

To apply it to a dataframe with variables of "Variable", "Description", "Unit", "Tier" (integer) and save a yaml file:

DF_To_yamlList <- function(.df){

  #assert columns in df include key ones
  assertthat::assert_that(is.data.frame(.df))
  assertthat::assert_that(all(c("Variable", "Description", "Unit", "Tier") %in% names(.df)))
  assertthat::assert_that(is.integer(.df$Tier), msg = "Column is not of integer type; please convert it.")

  lapply(1:nrow(.df), function(x){

    .df %>% dplyr::slice(x) %>%
      select(Variable, Description, Unit, Tier) %>%
      group_by(Variable) %>%
      nest() %>% ungroup() %>%
      mutate(data = list(Variable = as.list(data %>% purrr::pluck(1) ) )) -> .df2

    names(.df2$data) <- .df2$Variable

    .df2$data
  }
  )
}

library(dplyr)
library(yaml)
library(tidyr)
library(purrr)

dataframe  %>%
  DF_To_yamlList %>%
  yaml::write_yaml("./dataframe.yaml")
danielhuppmann commented 3 months ago

Thanks @realxinzhao, but keeping this as an open issue does not really make sense. If you want to keep this code snippet in this repository, I suggest to start a PR for a new folder "R-utils" with this script (and sufficient documentation).

realxinzhao commented 3 months ago

Sounds good. Thanks, @danielhuppmann