Home > database >  Input variable in a function as part of new filename
Input variable in a function as part of new filename

Time:11-17

I would like to use a function to pull variables from a dataset and then save as a new txt file. My R code using mtcars is below.

I ran into a problem when saving this new txt file. Because my var1 was am, I would like the new filename to be output_am1.txt. If I use vs as var1 then I would like the new filename to be output_vs1.txt.

In other words, I would like to add quotes around my input variable so that it can be saved as part of the new filename using paste0.

library(tidyverse)
library(janitor)
library(skimr)
f1 = function(dataset, var1, var2){
  # Use tabyl to check var1 
  print(tabyl(dataset, {{var1}}))
  
  # Create a new dataset by keeping those var1 == 1
  df = dataset %>% filter({{var1}} == 1)
  print(tabyl(df, {{var1}}))
  
  df1 = df %>% select(mpg, cyl, disp, hp, drat, {{var1}}, {{var2}})
  # Get a summary of this new dataset using skim():
  skim(df1)
  
  # Output as a txt file:
  write.table(df1,
              paste0("Desktop/output_",
                     var1, # !! Where I ran into problem
                     "1.txt"),
              sep = "\t", row.names = F, quote = F)
}

f1(mtcars, var1 = am, var2 = carb)

CodePudding user response:

One option would be to use rlang::ensym to convert to a symbol and rlang::as_label to convert to a character:

library(tidyverse)

tmp <- tempdir()

f1 <- function(dataset, var1, var2) {
  df <- dataset %>% filter({{ var1 }} == 1)
  df1 <- df %>% select(mpg, cyl, disp, hp, drat, {{ var1 }}, {{ var2 }})

  write.table(df1,
    paste0(
      paste0(tmp, "/output_"),
      rlang::as_label(rlang::ensym(var1)),
      "1.txt"
    ),
    sep = "\t", row.names = F, quote = F
  )
}

f1(mtcars, var1 = am, var2 = carb)

list.files(tmp, "\\.txt")
#> [1] "output_am1.txt"
  • Related