Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read multiple values as character vectors from an external file

I am currently reading data from a .csv that looks like this:

param_file <- tribble(
  ~variable, ~value,
  "year", "2023",
  "version", "Saint_XL, Sinner_XY",
  "metric", "ATE, OFCE"
)

I then need to load the variable and its value as character vectors so I am doing this, with dplyr:

year <- param_file %>% filter(variable == "year") %>% pull(value)
version <- param_file %>% filter(variable == "version") %>% pull(value)
metric <- param_file %>% filter(variable == "metric") %>% pull(value)

This works for single values, i.e.
year = "2023",

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but the variables with multiple values are being loaded as one value i.e.
"Saint_XL, Sinner_XY"
and
"ATE, OFCE"

Here is the desired output:

> year
[1] "2023"
> version
[1] "Saint_XL"  "Sinner_XY"
> metric
[1] "ATE"  "OFCE"

i.e. character vectors which would otherwise appear in the Environment Values as:
chr[1:2] "Saint_XL" "Sinner_XY"

A dplyr solution would really be appreciated. (Or any useful suggestions around loading variables and assigning values)

>Solution :

With separate_rows():

library(tidyverse)

param_file <- tribble(
  ~variable, ~value,
  "year", "2023",
  "version", "Saint_XL, Sinner_XY",
  "metric", "ATE, OFCE"
)

new_file <- param_file |> 
  separate_rows(value, sep = ",") |> 
  mutate(value = str_squish(value))

year <- new_file %>% filter(variable == "year") %>% pull(value)
version <- new_file %>% filter(variable == "version") %>% pull(value)
metric <- new_file %>% filter(variable == "metric") %>% pull(value)

year
#> [1] "2023"
version
#> [1] "Saint_XL"  "Sinner_XY"
metric
#> [1] "ATE"  "OFCE"

Created on 2024-03-17 with reprex v2.1.0

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading