rfunctionpins

How to pass a dataframe as object and as string in a function


I would like to customize the pin_write function from pins package:

The original works this way:

library(pins)

# create board: 
board_versioned <-  board_folder("your path", versioned = TRUE)

board_versioned %>% 
  pin_write(iris, "iris")

# gives:
# Guessing `type = 'rds'`
# Creating new version '20221030T182552Z-f2bf1'
# Writing to pin 'iris'

Now I want to create a custom function:

library(pins)
my_pin_write <- function(board, df) {
  board %>% 
    pin_write(df, deparse(substitute(df)))
}

my_pin_write(board_versioned, iris)

#gives: 
# Guessing `type = 'rds'`
# Replacing version '20221030T182736Z-f2bf1' with '20221030T182750Z-f2bf1'
# Writing to pin 'df'

The problem is Wrting to pin 'df' . I would expect: Writing to pin 'iris'

I can't manage how to pass the dataframe as name as string in this situation. Many thanks!


Solution

  • You are using a pipe call. In that case the df will be searched within the piped environment, and if not found, use df You have 2 options, do not use the pipe, ie

     pin_write(board, df, deparse(substitute(df)))
    

    for substitute to use the function environment or if you use the pipe, call the substitute function outside of the pipe. eg

    nm <- deparse(substitute(df))
    board %>% 
       pin_write(df, nm)
    

    You could decide to use the rlang::enxpr function:

     board %>%
       pin_write(df, deparse(rlang::enxpr(df)))