0

If I observe a convention of saving my file paths as variables with the common prefix "file_", it seems I could create a wrapper function for read_rds() that would name my read files based on whatever text came after "file_" in the file path's name.

I run into trouble when I evaluate the name I want the read file to take.

library(here)
library(readr)
library(stringr)

file_survey <- here("my_survey_2019.rds")

my_read_rds <- function(file){
  name <- deparse(substitute(file))
  name <- stringr::str_remove(name, "^file_")
  eval(name) <- readr::read_rds(file) # Does not work
}

my_read_rds(file_survey) # would ideally create a dataframe named `survey`
3
  • 1
    This type of behavior isn't encouraged in R. Functions shouldn't have "side effects" or create variables outside their scope. The "normal" way to do this is survey <- read_rds(file). This makes functions much easier to deal with and to be called from inside other functions. Commented Apr 26, 2019 at 17:01
  • that is a good point Commented Apr 26, 2019 at 17:05
  • @MrFlick "Side effect" is a functional programming terminology, but it's not the only way to program in R. For example, data.table does not follow a functional programming paradigm, yet it's one of the most popular libraries. People should program the way that they want to, if it makes sense to them or if they have a system. Commented Apr 26, 2019 at 17:13

1 Answer 1

1

You can use assign.

my_read_rds <- function(file){
  name <- deparse(substitute(file))
  name <- stringr::str_remove(name, "^file_")
  assign(name, readr::read_rds(file), envir=globalenv())
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.