When to create a function vs. as_mapper

Suppose I have the following code. This code will take a string containing a file path to a .txt file and read it in as a tibble and then rename the column y to whatever the filename was. I'm curious if I'm adding too much syntactic sugar and sacrificing easy readability or consistent programming principles. When is it advisable to use as_mapper() vs creating a function?

# Clean up file name to add to data set
clean_name <- compose(quo_name,
                      partial(str_remove, pattern = ".txt"),

# Function to read in the data and make proper adjustments
read_and_rename <- as_mapper(
  ~ read_csv(.x) %>%
    mutate(x = x + 215833) %>% 
    rename(time = x,
           !!clean_name(.x) := y) %>%
    gather(key = "test", value = "temp", -time)

Check out Colin Fay's writeup on purrr - he gets into some use cases for as_mapper().

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.