0

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!

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • 4
    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 enviironment or if you use the pipe, call the `substitute` function outside of the pipe. eg `nm <- deparse(substitute(df))` and then do `board %>% pin_write(df, nm)`. You could decide to use the `rlang::enxpr` function: `board %>%pin_write(df, deparse(rlang::enxpr(df)))` – Onyambu Oct 30 '22 at 19:40
  • @onyambu. Very useful. Please send as answer! – TarJae Oct 30 '22 at 19:56

3 Answers3

2

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)))
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

We could do

my_pin_write <- function(board, df) {
  board %>% 
     pin_write(df, rlang::as_string(rlang::ensym(df)))
 }

-testing

> my_pin_write(board_versioned, iris)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Another option is to replace magrittr's pipe (%>%) by the R native pipe (|>) that is available since R 4.1.0.

library(pins)

board_versioned <-  board_folder("your path", versioned = TRUE)

my_pin_write <- function(board, df) {
  board |>
    pin_write(df, deparse(substitute(df)))
}

my_pin_write(board_versioned, iris)
#> Guessing `type = 'rds'`
#> Creating new version '20221031T091813Z-911fb'
#> Writing to pin 'iris'

Created on 2022-10-31 with reprex v2.0.2

bretauv
  • 7,756
  • 2
  • 20
  • 57